我想链接一些任务,但如果我没有触发 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/