views:

105

answers:

4

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?

A: 

One better way is to use something like Windows Server AppFabric, which has notions of recurring tasks, error handling, and management built in. You just write the actual code you need. Unfortunately, it's bleeding edge today, but it's what I would choose for new development of this kind.

Craig Stuntz
Very cool but unfortunately they are running Windows XP SP 2 where I'm currently at. I'm actually using TopShelf to manage the service side of things which is nice but doesn't do the recurring stuff.
ShaneC
[They should really upgrade, then.](http://support.microsoft.com/gp/lifean31)
Craig Stuntz
+4  A: 

You could try using a System.Threading.Timer:

Timer tmr = new Timer(DoSomething, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 10, 0))
What would that gain me compared to the AutoResetEvent?
ShaneC
It would eliminate the AutoResetEvent and the tedious logic that goes with it. Also DoSomething will run in its own ThreadPool thread.
rather than running your loop, the timer will call out to your DoSomething() directly.In your stop() method you just have to stop the timer.
Josh Sterling
That makes sense. Thanks!
ShaneC
A: 

What about using Windows Workflow Foundation? I think its quite oriented to that kind of tasks.

You can could start the appruntime through your program, and then let the WWF app take care of things.

Francisco Noriega
Workflow Foundation seems like a massive amount of overkill for such a simple problem. I'm also leery of using it after the whole v4 means rewrite.
ShaneC
A: 

This won't run every 10 minutes; it will be very close to every 10 minutes if DoSomething is a quick process. The next run will happen 10 minutes are DoSomething completes.

You could use a job scheduler like Quartz.Net.

Austin Salonen
Good point. Yes that's actually what we do want to happen but thanks for pointing that out.
ShaneC