Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DispatcherTimer not firing Tick event

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?

like image 339
harryovers Avatar asked Mar 22 '11 15:03

harryovers


1 Answers

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!");
}
like image 126
Reed Copsey Avatar answered Sep 20 '22 08:09

Reed Copsey