[英]Task does not complete if another task with in it gets cancelled
In this code, the task t
will never complete (never outputs to the console) if I cancel the token, even though the token is not used for t
and only used for a task inside t
在此代码中,如果我取消令牌,任务
t
将永远不会完成(永远不会输出到控制台),即使令牌不用于t
并且仅用于t
内的任务
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
Task t = Task.Factory.StartNew(async () =>
{
await Task.Delay(1000, token);
Console.WriteLine("Task Completed");
});
source.Cancel();
How can I cancel the token but also let the task complete如何取消令牌但也让任务完成
Notes:笔记:
I tried using Task.Run
instead, and got the same output我尝试改用
Task.Run
,并得到相同的输出t.IsCompleted
will stay false indefinitely (task will never complete) t.IsCompleted
将无限期保持错误(任务永远不会完成)
The delay task does complete延迟任务完成
You can make the t
to survive the cancellation, by handling and suppressing the OperationCanceledException
that is thrown by the Task.Delay
:您可以通过处理和抑制由
Task.Delay
引发的OperationCanceledException
来使t
在取消中存活:
Task t = Task.Run(async () =>
{
try { await Task.Delay(1000, token); } catch (OperationCanceledException) { }
Console.WriteLine("Task Completed");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.