gpt4 book ai didi

c# - 当没有字节写入超过给定时间段时如何取消流 CopyToAsync

转载 作者:行者123 更新时间:2023-12-03 22:29:48 25 4
gpt4 key购买 nike

我想检测 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 , CancellationTokenSourceStream

关于c# - 当没有字节写入超过给定时间段时如何取消流 CopyToAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61732947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com