问题描述
根据文档 Task.Run(Action,CancellationToken)
在任务取消后抛出 TaskCanceledException
.
According to documentation Task.Run(Action, CancellationToken)
throws TaskCanceledException
when the task has been canceled.
Task.Run(Action,CancellationToken)
到底何时抛出 TaskCanceledException
?尚不清楚必须满足什么条件才能引发此异常.
When exactly does Task.Run(Action, CancellationToken)
throw TaskCanceledException
? It is not clear what conditions must be met for this exception to be thrown.
推荐答案
似乎有些混乱(文档可能会引起误解).
There seems to be some confusion (and the documentation might be misleading).
调用 Task.Run
方法将从不抛出 TaskCanceledException
(至少对于当前实现而言).与 ArgumentNullException
和 ObjectDisposedException
不同,当"action参数为null"和与cancellationToken关联的CancellationTokenSource被处置时"会同时引发.分别.
Inoking the Task.Run
method would never throw TaskCanceledException
(at least with the current implementation). Unlike ArgumentNullException
and ObjectDisposedException
that are thrown synchronously when the "The action parameter was null" and "The CancellationTokenSource associated with cancellationToken was disposed." respectively.
Task.Run
返回一个 Task
,可以使用 CancellationToken
参数取消该操作(有关取消操作的更多信息,请参见此处),然后通过 await任务等待它
, task.Wait()
, task.Result
等,将抛出 TaskCanceledException
(可能包装在 AggregateException
)
Task.Run
however returns a Task
that may be canceled using the CancellationToken
parameter (more on cancellation in here) and waiting on it with await task
, task.Wait()
, task.Result
, etc. would throw a TaskCanceledException
(possibly wrapped in an AggregateException
)
Task<int> task = null;
try
{
task = Task.Run(() => 5, new CancellationToken(true));
}
catch (TaskCanceledException)
{
Console.WriteLine("Unreachable code");
}
try
{
int result = await task;
}
catch (TaskCanceledException)
{
Console.WriteLine("Awaiting a canceled task");
}
如果文档中有两节可能的例外情况,可能会更清楚:
It might be clearer if the documentation had 2 sections of possible exceptions:
- 常规"同步异常(例如
ArgumentNullException
和ObjectDisposedException
) - 异步"异步异常,只能通过等待返回的任务来抛出(例如
TaskCanceledException
)
这篇关于Task.Run(Action,CancellationToken)何时会引发TaskCanceledException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!