我想检测Stream.CopyToAsync操作停顿,并检测超过1分钟的时间没有字节被复制。
那怎么办?
您需要定期检查Stream.Length
,如果没有进度,请取消使用CancellationTokenSource
。这是基本上使用计时器来定期检查复制是否有进展的代码。
using System.IO;
using System.Threading;
using System.Threading.Tasks;
var copyingCompleted = false;
var copyBufferSize = 4096;
var interval = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
var initialTimeoutMilliseconds = -1;//inifinite
var timer = new Timer(OnTimerElapsed,null,initialTimeoutMilliseconds,interval);
var cts = new CancellationTokenSource();
long streamLength = 0;
Stream srcStream = null;//should be your sourceStream
Stream dstStream = null;//should be your destination stream
await Copy(srcStream,dstStream,cts.Token);
public async Task Copy(Stream src,Stream dst, CancellationToken cancellationToken){
timer.Change(interval,interval);
try{
await src.CopyToAsync(dst,copyBufferSize, cancellationToken);
}
finally{
copyingCompleted = true;
}
}
public void OnTimerElapsed(object state){
if(copyingCompleted){
//stop the timer
timer.Change(-1,-1);
return;
}
//check if the copying has progressed since the last interval callback was invoked
if(dstStream.Length > streamLength){
//copy has progressed, I will check you in the next interval
streamLength = dstStream.Length;
return;
}
//you didn't make any progress, I am cancelling the copy process
cts.Cancel();
}
这不是完整的实现,你需要采取处置的一次性资源,包括护理Timer
,CancellationTokenSource
和Stream
小号
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句