Task.Wait (CancellationToken) Method

Can someone explain to me the use of Task.Wait (CancellationToken) overload? MSDN really talks a lot about this ...

So I usually handle task cancellation:

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 a token to the Wait method?

+6
source share
2 answers

Consider the case when you want to cancel waiting for a task without actually canceling the task itself ... either because the task does not handle the cancellation, or because you really want to continue working with the task, but (say) answer the user: "It will take some time ... but it's still ongoing. It's safe to close the browser. " (Or whatever.)

+13
source

This is found in the Microsoft technical documentation:

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

+3
source

Source: https://habr.com/ru/post/950504/


All Articles