DispatcherTimer not firing Tick event

harryovers picture harryovers · Mar 22, 2011 · Viewed 18.7k times · Source

I have a DispatcherTimer i have initialised like so:

static DispatcherTimer _timer = new DispatcherTimer();

static void Main()
{
    _timer.Interval = new TimeSpan(0, 0, 5);
    _timer.Tick += new EventHandler(_timer_Tick);
    _timer.Start();
}
static void _timer_Tick(object sender, EventArgs e)
{
    //do something
}

The _timer_Tick event never gets fired, have i missed something?

Answer

Reed Copsey picture Reed Copsey · Mar 22, 2011

If this is your main entry point, it's likely (near certain) that the Main method exits prior to when the first DispatcherTimer event could ever occur.

As soon as Main finishes, the process will shut down, as there are no other foreground threads.

That being said, DispatcherTimer really only makes sense in a use case where you have a Dispatcher, such as a WPF or Silverlight application. For a console mode application, you should consider using the Timer class, ie:

static System.Timers.Timer _timer = new System.Timers.Timer();

static void Main()
{
    _timer.Interval = 5000;
    _timer.Elapsed  += _timer_Tick;
    _timer.Enabled = true;

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey(); // Block until you hit a key to prevent shutdown
}
static void _timer_Tick(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("Timer Elapsed!");
}