在c# . net 4.0中为异步调用指定CancellationTokenSource超时

本文关键字:调用 CancellationTokenSource 超时 异步 net | 更新日期: 2023-09-27 17:49:39

我正在尝试从Azure下载一个固定超时的blob。我在。net 4.5中有以下工作代码。但是,当我尝试在。net 4.0中重写时,我找不到为CancellationTokenSource指定超时的方法。你能帮帮我吗?

var cts = new CancellationTokenSource((int)TimeSpan.FromSeconds(30).TotalMilliseconds);
using (var memoryStream = new System.IO.MemoryStream())
{
    Task task = blockBlob.DownloadToStreamAsync(memoryStream, cts.Token);
    await task.ConfigureAwait(false);
    ...
}

另外,我发现如果在指定的时间内没有下载blob,下面的代码(在4.0中)会超时。我不确定在使用时是否有什么地方需要注意。

Task task = blockBlob.DownloadToStreamAsync(memoryStream);
task.Wait((int)TimeSpan.FromSeconds(30).TotalMilliseconds);

在c# . net 4.0中为异步调用指定CancellationTokenSource超时

在4.5框架之前没有办法指定CancellationTokenSource超时。我建议你使用下一种方法

var cts = new CancellationTokenSource();
var timer = new System.Timers.Timer(timeout) {AutoReset = false};
timer.Elapsed += (sender, eventArgs) => { cts.Cancel(); };
var task = new Task(action, cts.Token);
task.Start();
timer.Start();

笨拙,但工作