I did some research and looking around and it seems the way to do this is using an AutoResetEvent. I quickly put this together and it seems to work and seems to be thread-safe. Can I have some feedback?
class Program
{
private Thread workerThread;
private AutoResetEvent aResetEvent;
private bool _continueProcessing;
private bool active;
private Object locker = new Object();
public Program()
{
workerThread = new Thread(DoSomeProcessing);
workerThread.IsBackground = true;
aResetEvent = new AutoResetEvent(false);
}
public bool ContinueProcessing
{
get
{
lock (locker)
{
return _continueProcessing;
}
}
set
{
if (value)
{
aResetEvent.Set();
}
else
{
aResetEvent.Reset();
}
lock (locker)
{
_continueProcessing = value;
}
}
}
public void DoSomeProcessing()
{
int i = 0;
try
{
while (active)
{
aResetEvent.WaitOne();
// do some work and sleep
lock (locker)
{
if (ContinueProcessing)
{
aResetEvent.Set();
}
}
}
}
catch(ThreadInterruptedException tie)
{
Console.WriteLine("Shutting down.");
}
// any shutdown processing
}
public void StopProcessing()
{
workerThread.Interrupt();
workerThread.Join();
}
public void PauseProcessing()
{
ContinueProcessing = false;
}
public void Continue()
{
ContinueProcessing = true;
}
public void StartProcessing()
{
ContinueProcessing = true;
active = true;
}
}
EDIT: Hi Again. I have used the feedback and I am much more satisfied with my implementation. Just one little thing that I would like to add, when I pause I would like to wait to make sure that the thread has paused and is no longer doing work. Is that possible? Maybe I should just replace the pause and resume with only start and stop and then on the stop do a thred.join(). Comments?