11

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.

ldam
  • 4,412
  • 6
  • 45
  • 76
  • 3
    As mentioned by [Stephen Cleary in comments to this question](http://stackoverflow.com/q/20660362/1180426), there's no clean way to abort long-running in-process work that is not cancellation-aware... – Patryk Ćwiek Mar 17 '14 at 14:11
  • So you're using a 3rd party .NET 3.5-based library. As there's no `Task` in .NET 3.5, what kind of API does this library expose? Is it `BeginXXX/EndXXX` APM pattern? – noseratio Mar 18 '14 at 03:40
  • It isn't 3rd party, it's in house. I can't change the library because it is in production. It doesn't use any patterns and doesn't use any threading at all. All it does is read several XML files and parse it into memory so I can access the data later. – ldam Mar 18 '14 at 06:46

2 Answers2

4

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.

NickC
  • 385
  • 1
  • 10
2

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

Community
  • 1
  • 1
i3arnon
  • 113,022
  • 33
  • 324
  • 344