Search code examples
c#multithreadingtask-parallel-librarycancellation-token

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?


Solution

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