How to make a task stop?

I use Taskwith the provided CancellationTokenSource, and in my task I always check to see if a cancellation is requested, and stop execution, if necessary, in parts of the code that I control. The problem is that as part of this task, I use very long methods from libraries that do not support cancellation and were compiled for .NET 3.5 (I use 4.5.1).

Depending on the input, these methods can work for several minutes (sometimes 10+). I do not want so much processing to be lost if the result is never used.

Is there any other way to force terminate Task? Perhaps I better make a thread in my task just to run these methods and kill those threads when the request is canceled.

+4
source share
2 answers

Your only option is to wrap these irreplaceable functions in a separate thread and simply terminate this thread upon cancellation. As mentioned by others Thread.Abort, this is an extremely dangerous operation. It terminates the stream without the need to clear resources that might be required. Use this as a last resort. Depending on when you interrupt, your program may be left in unwanted conditions.

+2
source

, ( , ) , - , , .

: Async

+2

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


All Articles