3

I've read in a bunch of places that I should stay away from Thread.Abort. And learned the hard way that it's true (it seem to have quite platform dependent behavior on Mono) :))

So what's the good/graceful way to terminate a thread from outside?

I understand that I can add a code like this:

if (terminateRequested) return;

or better

if (terminateRequested) throw new MyTerminateThreadException();

but in real world case where thread code is spread over multiple C# files it quickly becomes an annoying and duplicated pattern.

And how about situations where thread is Sleeping, waiting for server connection, mutex or executing code which is not mine? How do you deal with those?

Paulius Liekis
  • 1,676
  • 3
  • 18
  • 26
  • 1
    http://stackoverflow.com/questions/3632149/question-about-terminating-a-thread-cleanly-in-net/3632642#3632642 - Possibly of help? – Peppermintology Nov 20 '14 at 23:33
  • 2
    There are just too many different scenarios to answer this question properly in a short amount of space. It really just depends on each specific scenario. That said, barring the use of `Thread.Abort()` (which I agree is an awful way to interrupt a thread), you're pretty much stuck checking some state somewhere if you want an actively-running thread to be interrupted. – Peter Duniho Nov 20 '14 at 23:34
  • 1
    Does Mono have the `Task` class available? If so, you could use a `CancellationToken` to interrupt a thread. – techvice Nov 20 '14 at 23:37

1 Answers1

1

I believe that Mono has the Task class available. I would recommend looking through using CancellationToken. Check out this Task Cancellation page for a better idea of executing a thread and cancelling it.

Community
  • 1
  • 1
techvice
  • 1,315
  • 1
  • 12
  • 24