c# - 如何使用 CancellationToken 链接异步任务?

标签 c# asynchronous task

我想链接一些任务,但如果我没有触发 CancellationToken,则有条件地继续执行。

我的目标是实现等同于

var cts = new CancellationTokenSource();
var cancellationToken = cts.Token;
var t = Task.Run(async () => {
    if (cancellationToken.IsCancellationRequested) return;
    await t1();
    if (cancellationToken.IsCancellationRequested) return;
    await t2();
    if (cancellationToken.IsCancellationRequested) return;
    await t3();
    if (cancellationToken.IsCancellationRequested) return;
    await t4();
});
var timeout = Task.Delay(TimeSpan.FromSeconds(4));
var completedTask = await Task.WhenAny(t, timeout);
if (completedTask != t)
{
    cts.Cancel();
    await t;
}

这就是我现在所拥有的并且它正在运行,尽管它也很冗长。

最佳答案

var cts = new CancellationTokenSource();
var t = Task.Run(async () => {
     await t1();
     await t2();
     await t3();
     await t4();
 }, cts.Token);

cts.CancelAfter(TimeSpan.FromSeconds(4));

try
{
     await t;
}
catch (OperationCanceledException)
{
     // The cancellation token was triggered, add logic for that
     ....
}

关于c# - 如何使用 CancellationToken 链接异步任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58456365/

相关文章:

c# - SQL Server 2012 FileTable 创建文件时性能下降(集成 Lucene.NET)

c# - 如何修改存储过程或 ASP.net 代码以在插入新行后获取自动生成的 Id

c# - Azure WebJob 访问被拒绝

javascript - Node.js 异步,但仅处理第一个肯定/定义的结果

c# - 如何取消来自不同类(class)的任务

c# - 异步 CTP 中的 `TaskEx.WhenAll` 是什么?

c# - 使用局部变量有什么好处?

c# - HttpClient 提供的不是真正的异步操作吗?

javascript - 将 Promise 中的解析函数分配给变量

c# - 如何在异步方法中抛出异常 (Task.FromException)