Nice way to abort a thread (no Thread.Abort)

I've read into a bunch of places where I should stay away from Thread.Abort. And found out that it is true (it looks like this is pretty platform dependent behavior in Mono) :))

So what's a good / neat way to interrupt a thread from the outside?

I understand that I can add code like this:

if (terminateRequested) return;

      

or better

if (terminateRequested) throw new MyTerminateThreadException();

      

but in the real world, where stream code is spread across multiple C # files, it quickly becomes an annoying and duplicated pattern.

What about situations where the thread is "Sleeping", waiting to connect to the server, a mutex, or executable code that is not mine? How do you deal with these problems?

+3


source to share


1 answer


I believe Mono has a class Task

. I would recommend browsing with CancellationToken

. Review this Canceling Task page for a better understanding of thread execution and canceling it.



0


source







All Articles