Question

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?

Was it helpful?

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

OTHER TIPS

Found this in a Microsoft white paper:

It is also interesting to note the existence of an overload for Task.Wait() that takes a CancellationToken with the signature Task.Wait(CancellationToken). This overload takes a token so that the wait can be canceled; this overload has nothing to do with canceling the task, but rather it can cause the wait to return prematurely. If Task.Wait(ct) is used and the wait is interrupted because it detects the token has been signaled, then an OperationCanceledException(ct) will be thrown to indicate that the wait operation was canceled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top