I a total threading n00b and I want to figure out a way to shut down a thread first by asking nicely, then by force.
I have a ProcessManager
class that starts a bunch of Process
class threads:
public class ProcessManager
{
private IProcessRepository _processRepository;
private List<Thread> _threads = new List<Thread>();
public ProcessManager(IProcessRepository processRepository)
{
_processRepository = processRepository;
}
public void StartAllProcesses()
{
foreach (var process in _processRepository.GetActiveProcesses())
{
var thread = new Thread(process.ProcessUntilStopped);
_threads.Add(thread);
thread.Start();
}
}
public void StopAllProcesses()
{
// What to do here?
}
}
public class Process
{
private bool _stopFlag = false;
public void ProcessUntilStoppped()
{
while (true)
{
if (_stopFlag) return;
// I don't want this call interrupted by Thread.Join(),
// but it's important for multiple Processes to be able to DoWork()
// simultaneously.
DoWork();
}
}
public void Stop()
{
_stopFlag = true;
}
}
How do I get my thread not to be interrupted while calling DoWork()
and instead wait until the next loop iteration to stop? (My understanding is that lock
would not be appropriate here because multiple threads have to be able to call DoWork()
while they're running, so there's no resource that needs to be mutually exclusive.)
How do I check to see if my thread has stopped nicely, and if not, force it to stop? (I am aware that Thread.Abort()
is bad karma.)
I figure this has to be a common problem with a fairly standard solution, but I'm not really familiar with the right nomenclature or .NET methods to call.