When does Task.Run (Action, CancellationToken) throw a TaskCanceledException?

According to the throws documentation when the task was canceled.Task.Run(Action, CancellationToken)TaskCanceledException

When exactly is Task.Run(Action, CancellationToken)throw TaskCanceledException? It is not clear what conditions must be met to exclude this exception.

+4
source share
2 answers

There seems to be some confusion (and the documentation may be misleading).

Task.Run throw TaskCanceledException ( , ). ArgumentNullException ObjectDisposedException, , " " "The CancellationTokenSource, cancelationToken ". .

Task.Run a Task, CancellationToken ( ) await task, task.Wait(), task.Result .. TaskCanceledException (, 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");
}

, , 2 :

  • "" (, ArgumentNullException ObjectDisposedException)
  • "" , (, TaskCanceledException)
+6

:

, .

:

. , .

, CancellationToken.IsCancelledRequested CancellationToken.ThrowIfCancelltionRequested. await .

0

All Articles