Can someone please explain to me to the usage of the Task.Wait(CancellationToken) overload? MSDN does say much about it...
This is how I usually handle task cancellations:
var source = new CancellationTokenSource();
var task = Task.Factory.StartNew(() =>
{
while (true)
{
source.Token.ThrowIfCancellationRequested();
}
}, source.Token);
try
{
task.Wait();
}
catch (AggregateException exc)
{
exc.Flatten().Handle(e => e is OperationCanceledException);
}
So when is it useful to pass the token to the Wait method?
A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.
The CancellationToken is used in asynchronous task. The CancellationTokenSource token is used to signal that the Task should cancel itself. In the above case, the operation will just end when cancellation is requested via Cancel() method.
TaskCanceledException(String, Exception, CancellationToken) Initializes a new instance of the TaskCanceledException class with a specified error message, a reference to the inner exception that is the cause of this exception, and the CancellationToken that triggered the cancellation.
Consider the case where you want to cancel waiting for the task, without actually cancelling the task itself... either because the task doesn't handle cancellation itself, or because you actually want to keep going with the task, but (say) respond to the user with "This is taking a while... but it's still in progress. It's safe to close your browser." (Or whatever.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With