December 2019
Intermediate to advanced
346 pages
9h 8m
English
We can create a task by passing CancellationToken as the second argument to the task constructor, as follows:
var sumTaskViaTaskOfInt = new Task<int>(() => Sum(5), token);var sumTaskViaFactory = Task.Factory.StartNew<int>(() => Sum(5), token);var sumTaskViaTaskRun = Task.Run<int>(() => Sum(5), token);
In the classic threading model, we used to call the Abort() method on a thread that was non-deterministic. This would stop the thread abruptly, thereby leaking memory if resources were unmanaged. With TPL, we can call the Cancel method, which is a cancellation token source that will, in turn, set up the IsCancellationRequested property on the token. The underlying method that's being executed by the task should watch ...
Read now
Unlock full access