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

标签 c# .net .net-core

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

相关文章:

C# 相当于 Java 中的通配符导入

c# - LINQ to Entities 相似代码

c# - 为什么这里要用锁?

c# - 设置 DatePicker 值

.net-core - 如何替换 .NET Standard 的 System.ComponentModel.DataAnnotations 类?

C# 使用 FileSystemWatcher 跟踪文件夹连接

c# - 禁用计时器 .. 为什么我不能?

c# - 在其他服务中访问 MVC DI 服务

c# - 从 .net core 3.1 中的 appsettings.json 获取值

c# - 下载 URL 列表