See it.
You cannot “cancel” an already running code — for the same reasons that you cannot “kill” a running thread. Therefore, the code run via Task.Run will run to the end, unless he himself analyzes the token and cancels himself.
However, the task will not be started if the token is already in the canceled state. Since launching Task 'a is a consumable thing, this is a good optimization.
In addition, the task will be associated with this token, and if the code in Method throws an exception through token.ThrowIfCancellationRequested , this exception will be considered related to the task. Thus, the task will be terminated in the Cancelled state, and not Faulted .
Source of information: https://social.msdn.microsoft.com/Forums/en-US/c2f614f6-c96c-4821-84cc-050b21aaee45/taskfactorystartnew-cancellation-token-parameter?forum=parallelextensions
Reproducing example:
async Task Run() { var cts = new CancellationTokenSource(); var ct = cts.Token; var t = Task.Run((Action)(() => // каст нужен! пояснение в конце ответа { while (true) { ct.ThrowIfCancellationRequested(); Thread.Sleep(200); } }), cts.Token); await Task.Delay(400); cts.Cancel(); try { await t; } catch (TaskCanceledException ex) { Console.WriteLine($"caught TaskCanceledException, task status = {t.Status}"); } catch (OperationCanceledException ex) { Console.WriteLine($"caught OperationCanceledException, task status = {t.Status}"); } }
This code falls into catch (OperationCanceledException ex) , and the status of the task is Canceled . And if you remove the token, then we also fall into catch (OperationCanceledException ex) , but the status is Faulted . In this case, runtime thinks that it was not the cancellation of the task that occurred, but simply some other extraneous exception.
(We get to TaskCanceledException if the task has been canceled before launch.)
(An error in the previous version of the code was that there was no explicit cast to Action [which is almost never needed!], And because of the infinite loop inside, the type driver could not decide whether it was overloading with Action or overloading with Func<Task> ! As a result he chose not what was needed, and rantaym believed that it was not the task that was canceled, but the process of its creation.)