Problem statement
I have a worker thread that basically scans a folder, going into the files within it, and then sleeps for a while. The scanning operat
I recommend to keep it simple:
while (m_shouldRun)
{
DoSomethingThatTakesSeveralSeconds();
for (int i = 0; i < 5; i++) // example: 5 seconds sleep
{
if (!m_shouldRun)
break;
Thread.Sleep(1000);
}
}
public void Stop()
{
m_shouldRun = false;
// maybe thread.Join();
}
This has the following advantages:
Stop
method needs to do is to set m_shouldRun
to false and (maybe) call Thread.Join
(if it is necessary for the thread to finish before Stop
is left). No synchronization primitives are needed (except for marking m_shouldRun
as volatile).