I am trying to validate the solution I came up for what I think is a fairly typical problem. I have a service running and every 10 minutes it should do something. I've 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 I can see is that I'm not doing any sort of locking around the isRunning modification in Stop() which gets called by another thread but I'm not sure I really need to? The worst that I think could happen is that it runs one extra cycle.
Beyond that are there any obvious problems with this code? Is there a better way to solve this problem that I'm unaware of?