Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Wait Method (CancellationToken)

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?

like image 210
Tsef Avatar asked Jul 29 '13 08:07

Tsef


People also ask

What is a CancellationToken?

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.

What is CancellationToken C# task?

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.

What is a task canceled exception?

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.


1 Answers

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.)

like image 138
Jon Skeet Avatar answered Oct 06 '22 13:10

Jon Skeet