The most correct and thread-safe way is to use WaitHandle to feed the signal when it should stop. I mainly use ManualResetEvent.
In your topic, you can:
private void RunThread() { while(!this.flag.WaitOne(TimeSpan.FromMilliseconds(100))) {
where this.flag is an instance of ManualResetEvent. This means that you can call this.flag.Set() from outside the thread to stop the loop.
The WaitOne method will return true only when the flag is set. Otherwise, it will expire after the specified timeout (100 ms in the example), and the thread will again go through the loop.
Mark Seemann Jun 27 '09 at 6:20 2009-06-27 06:20
source share