Creating your own thread is not something that I do lightly. There are so many alternatives these days where framework does "dirty job" for you.
However, sometime making your own thread is way to go. I found that mostly I use same code in order to cancel it.
Idea is creating ManualResetEvent that we can check fairly quick from thread loop. Once that event switches it's value to true, our thread should terminate.
private ManualResetEvent _cancelEvent;
private Thread _thread;
public void Start() {
_cancelEvent = new ManualResetEvent(false);
_thread = new Thread(Run);
_thread.IsBackground = true;
_thread.Name = "EntranceBarrier";
_thread.Priority = ThreadPriority.AboveNormal;
_thread.Start();
}
public void Stop() {
_cancelEvent.Set();
while (_thread.IsAlive) { Thread.Sleep(10); } //wait until it is really stopped
}
bool IsCanceled {
get { return _cancelEvent.WaitOne(0, false); }
}
void Run() {
while (!IsCanceled) {
//some code
if (this.IsCanceled) { return; }
//some code
}
}
P.S. This will terminate thread gently and it only works if event is checked often. If you have code that is waiting for system event, this is not solution for you.