I am trying to verify the correctness of the solution, which I consider to be a fairly typical problem. I have a service, and every 10 minutes he has to do something. I ended up with the following:
private AutoResetEvent autoResetEvent = new AutoResetEvent(true);
private bool isRunning = true;
public void Execute()
{
while(isRunning)
{
DoSomething();
if(isRunning)
{
autoResetEvent.WaitOne(new Timespan(0, 10, 0));
}
}
}
public void Stop()
{
isRunning = false;
autoResetEvent.Set();
}
The immediate potential problems that I see is that I do not make any locks in the isRunning modification in Stop (), which is called by another thread, but I'm not sure what I really need? The worst that I think can happen is that it starts one extra loop.
Also, are there any obvious issues with this code? Is there a better way to solve this problem that I don't know about?
source
share