How to handle recurring execution?

Posted by ShaneC on Stack Overflow See other posts from Stack Overflow or by ShaneC
Published on 2010-05-14T16:16:45Z Indexed on 2010/05/14 16:24 UTC
Read the original article Hit count: 222

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 bool isRunning = true;

public void Execute()
{
    while(isRunning)
    {
       if(isRunning)
       {
         DoSomething();
         m_AutoResetEvent.WaitOne(new Timespan(0, 10, 0));
       }
    }
}

public void Stop()
{
    isRunning = false;
    m_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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about best-practices