harryovers
harryovers

Reputation: 3138

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?

Upvotes: 20

Views: 23012

Answers (6)

Maxence
Maxence

Reputation: 13306

If the timer is created in a worker thread, the Tick event will not fire because there is not dispatcher.

You have to create the timer in the UI thread or use the DispatcherTimer constructor which takes a Dispatcher instance as the second argument, passing the UI dispatcher:

var timer = new DispatcherTimer(DispatcherPriority.Background, uiDispatcher);

Upvotes: 5

You have to use

static void DispatcherTimer_Tick(object sender, object e)
{

}

in the place of timer_tick event

Upvotes: -3

poindexter12
poindexter12

Reputation: 1783

You have to start a dispatcher in order for the dispatcher to "do" any events. If you are running inside of a WPF application, this should happen automatically. If you are running in a console (which it looks like), this will never fire because there isn't a dispatcher. The easiest thing you can do is try this in a WPF application and it should work fine.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941715

You missed Application.Run(). Tick events cannot be dispatched without the dispatcher loop. A secondary issue is that your program immediately terminates before the event ever could be raised. Application.Run() solves that too, it blocks the Main() method.

Upvotes: 5

user623892
user623892

Reputation:

because the main method thread ended before the tick was called.

Upvotes: 6

Reed Copsey
Reed Copsey

Reputation: 564461

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!");
}

Upvotes: 37

Related Questions