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?
I believe that Mono has the
Task
class available. I would recommend looking through usingCancellationToken
. Check out this Task Cancellation page for a better idea of executing a thread and cancelling it.