Continue with canceled task

I defined the following task

var t = Task.Factory.StartNew( () => LongRunningMethod( cancellationToken ), cancellationToken ); t.ContinueWith( Callback, cancellationToken, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext() ); 

Inside LongRunningMethod , I check if the cancellation token has a revocation, and if so, then I return from the method. It works very well.

However, Callback is not called in this scenario. The callback is called if you replace the second line above with

 t.ContinueWith( x => Callback( x, cancellationToken ), TaskScheduler.FromCurrentSynchronizationContext() ); 

In this situation, the task still believes that it has completed.

Why does the first call not work? I got the impression that TaskContinuationOptions.None means that the callback will be called regardless of the state of the thread.

I cancel the task by calling:

 _cancellationTokenSource.Cancel(); 

Due to some note, the need to skip cancellation tokens seems to be the main drawback of the task library design.

+6
source share
1 answer

In your continuation task, you will receive a CancellationToken, which you will cancel. This means that the continuation task, while unartitioned, is canceled. Do not pass this token to something you do not want to cancel.

CancellationToken is designed to immediately cancel the entire schedule of actions. You can exclude material from cancellation without transferring a token.

+12
source

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


All Articles