Suppose you have a class where you start some background thread: this class could have a Run() method that starts up these threads, and a Stop() method that stops them properly. Some of these background threads may have been created manually, others may be managed by a Timer, which is activated when the above Run() method is invoked.
public void Run()
{
m_ShutdownRequested = false; // shutdown flag disabled
m_WorkerThread = new Thread(Work) { IsBackground = true };
m_WorkerThread.Start();
// ...
}
public void Stop()
{
lock (m_LockInput)
{
m_ShutdownRequested = true; // shutdown flag enabled
Monitor.Pulse(m_LockInput);
}
m_WorkerThread.Join(m_ShutdownTimeout);
}
Suppose that the Run() method is invoked when the user clicks the Run button on the UI. Similarly, the Stop() method is invoked when the user clicks the Stop button on the UI. How should these methods be implemented in order to be invoked via the UI? Should they both be asynchronous? If yes, how to deal with the possibility that some thread can not stop?
Suppose that after executing the Stop() method, some threads were not stopped. At this point, if the user click the Run button again, the instance of that class would have some threads not yet stopped. However, starting the Run() method, the previous m_WorkerThread instance is overwritten: what happens if this overwriting is performed when the thread is not yet finished?
No overwriting of the thread occurs, you are simply creating a new instance of a variable and assigning it. The thread that was running will continue to run, but since you no longer have a reference to it, you won’t be able to get back to it. After the thread exits, the GC may cleanup up the thread instance, or it may not.