0

What am I trying to achieve?

I am trying to cancel a long running task from within another task using a CancellationToken. It's impossible for me to handle the cancellation and throw in the long running task because it will never touch the code that handles the cancellation (the task processes a bad regex pattern that takes forever anyway this is not important). I tried to handle from within another Task and poll for the cancellation request, and when I call ThrowIfCancellationRequested() it actually throws in that thread. So the long running task is still alive and hanging.

How I solved this

Well instead of using token's ThrowIfCancellationRequested() i acually called Abort() on the long running task's Thread and it works like charm.

And my question is: I am pretty sure it's not very elegant and I wanted to know if it is OK what I did there and how else can I approach this situation?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Mihail Georgescu
  • 405
  • 3
  • 14
  • 1
    http://stackoverflow.com/questions/4359910/is-it-possible-to-abort-a-task-like-aborting-a-thread-thread-abort-method – Khanh TO Feb 26 '16 at 13:21
  • Thank you sir. So the very first lines...This in not OK! It's terrible. – Mihail Georgescu Feb 26 '16 at 13:24
  • 1
    Thread.Abort isn't doing what you think it does. [Refer my related answer here](http://stackoverflow.com/questions/27561976/check-if-thread-finished-its-method-before-killing-it-c-sharp) – Sriram Sakthivel Feb 26 '16 at 13:32
  • @SriramSakthivel thank you sir! Will think twice before using Abort() again. The only solution here in my situation is to be careful with regex patterns and backtracking. Just trying to learn regex. Thank you again. – Mihail Georgescu Feb 26 '16 at 13:41
  • 5
    Be aware that `Regex` provides option to specify timeout. If timeout is what you're trying to achieve, simply use the [overload which supports timeout.](https://msdn.microsoft.com/en-us/library/hh160201(v=vs.110).aspx) – Sriram Sakthivel Feb 26 '16 at 14:08
  • Where does the regex come in here? If you have a regex issue, please post the regex that is probably causing a catastrophic backtracking. – Wiktor Stribiżew Feb 26 '16 at 14:12
  • @WiktorStribiżew that is not the point! It just came into discussion , the main question was about long running tasks , I just pointed to the type of long running task I am doing. We are way off topic right now. – Mihail Georgescu Feb 26 '16 at 14:25
  • @SriramSakthivel yes that is true sir. – Mihail Georgescu Feb 26 '16 at 14:26

1 Answers1

3

Thread.Abort is evil because it is highly dangerous. Cancellation in .NET (and any other platform I'm aware of) is cooperative. Either make the action cancel itself on demand or isolate it so that you can just ignore it.

Community
  • 1
  • 1
usr
  • 168,620
  • 35
  • 240
  • 369