Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force a Task to stop?

I am using a Task with a CancellationTokenSource provided, and within my task I always check if cancellation is requested and stop executing if requested - in the parts of the code that I control. The problem is that within this task, I use very long running methods from libraries that don't support cancelling and were compiled for .NET 3.5 (I'm using 4.5.1).

Depending on the input, these methods can run for several minutes (sometimes 10+). I don't want to let so much processing go to waste if the result is never going to be used.

Is there any other way to forcefully terminate a Task? Perhaps I am better off making a thread within my task just to run these methods, and kill those threads whenever cancellation is requested.

like image 568
ldam Avatar asked Mar 17 '14 14:03

ldam


People also ask

How do you close a task that won't close?

A basic troubleshooting step when programs freeze up is pressing Alt + F4. This is the Windows keyboard shortcut for closing the current process, equivalent to clicking the X icon in the upper-right corner of a window.

How do you force quit a program on Windows?

Simple as this. Press Ctrl + Alt + Delete and select Task Manager or Ctrl + Shift + Esc to bring Task Manager up directly. Select the application you're trying to close and click End task.


2 Answers

Your only option is to wrap these non-cancelable functions within a separate thread and just terminate that thread upon cancelation. As mentioned by others Thread.Abort is an extremely unsafe operation. It terminates the thread without allowing any resource cleanup that may be needed. Use this as a last resort. Depending on when you abort your program might be left in undesired states.

like image 190
NickC Avatar answered Oct 03 '22 19:10

NickC


It depends on your specific implementation, but you can try and make the long operation throw an exception (as long as it handles that well) after a timeout has passed, and catch it in the code you control.

You can find examples in this question: Async network operations never finish

like image 25
i3arnon Avatar answered Oct 03 '22 18:10

i3arnon