Stop task without ThrowIfCancellationRequested

I have a task that I want to cancel.

The usual way to do this is with a CancellationToken .

 this.task = new SpecialTask(() => { for (int i = 0; i < ushort.MaxValue; i++) { CancelToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }, this.CancelToken); 

However, in the real world everything is so simple. Our asynchronous code cannot be encoded, and it looks like this:

 this.task = new SpecialTask(() => { CancelToken.ThrowIfCancellationRequested(); Operation1(); CancelToken.ThrowIfCancellationRequested(); Operation267(CancelToken); CancelToken.ThrowIfCancellationRequested(); object232.Operation345(); CancelToken.ThrowIfCancellationRequested(); object99.Operation44(CancelToken); CancelToken.ThrowIfCancellationRequested(); Operation5(CancelToken); ... CancelToken.ThrowIfCancellationRequested(); Operation...n(CancelToken); }, this.CancelToken); 

I used random numbers for the names of objects and methods to show that no loop could be created at all.

What bothers me the most is that I have to keep writing the same CancelToken.ThrowIfCancellationRequested() again and again.

And, as if that’s not enough, I need to drag the CancellationToken all over my code to stop the long-running operation - according to Microsoft - at the right time.

Having said that, is there any way to refuse callbacks that reflect my code?

We also know that when using

 try { task.Wait(cancelToken); } catch(OperationCancelledException) { } 

a OperationCancelledException is thrown and broken for the Wait method. However, the lengthy operation performed by the task does not stop if from time to time there are no CancelToken.ThrowIfCancellationRequested() checks.

Is it possible to stop an internal operation when an exception is caught to wait?

+6
source share
1 answer

You can reorganize your code in a loop to avoid re-canceling between each line:

 var actions = new List<Action>() { ()=>Operation1(), ()=>Operation267(CancelToken), ()=>object232.Operation345(), //... }; foreach (var action in actions) { action(); CancelToken.ThrowIfCancellationRequested(); } 
+2
source

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


All Articles