tags:

views:

39

answers:

2

I am using a Timer to run an event periodically on a reasonably long interval (2 minutes). This is working fine. However I would like the event to fire immediately when the timer is created (instead of waiting 2 minutes).

Note that I can't do this just by calling the method, since it takes some time to run and would block the application. I need the timer to fire as normal and run the event in a separate thread.

The best way I can think of doing this at the moment is subclassing the timer and creating a TriggerManually method that would do something like this:

  • Turn auto reset off
  • Set the interval to 1ms
  • Enable the timer

This would trigger the elapsed event straight away, and I could put all the settings back to normal.

Seems a bit roundabout though. Is there a better way to do it?

+3  A: 

Could you use a System.Threading.Timer instead ? It has a constructor that lets you choose the interval as well as the delay (which can be set to 0 to begin immediately). http://msdn.microsoft.com/en-us/library/2x96zfy7.aspx

Gishu
@Gishu: +1 even better (forgot about that!) :)
Mitch Wheat
@Mitch - just proves that you're human inspite of your insane rep :)
Gishu
Yep, this works. System.Threading.Timer is a bit more difficult to use, but it does what I need. Thanks!
Nathan Reed
+1  A: 

Couldn't you just call your event handler for the elapsed event manually?

Even if you were expecting it to execute on a thread pool thread, you could invoke it.

class Blah
{
    private Timer mTimer;

    public Blah()
    {
        mTimer = new Timer(120000);

        ElapsedEventHandler handler = new ElapsedEventHandler(Timer_Elapsed);
        mTimer.Elapsed += handler;
        mTimer.Enabled = true;

        //Manually execute the event handler on a threadpool thread.
        handler.BeginInvoke(this, null, new AsyncCallback(Timer_ElapsedCallback), handler);
    }

    private static void Timer_Elapsed(object source, ElapsedEventArgs e)
    {
        //Do stuff...
    }

    private void Timer_ElapsedCallback(IAsyncResult result)
    {
        ElapsedEventHandler handler = result.AsyncState as ElapsedEventHandler;
        if (handler != null)
        {
            handler.EndInvoke(result);
        }
    }
}
Rob Cooke