The most correct and thread-safe way is to use a WaitHandle to signal to the thread when it's supposed to stop. I mostly use ManualResetEvent.
In your thread, you can have:
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 only return true when the flag is set. Otherwise, it will time out after the specified timeout (100 ms in the example) and the thread will run through the loop once more.