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?

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

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


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.


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.


You have to use

static void DispatcherTimer_Tick(object sender, object e)
{

}

in the place of timer_tick event


Need Your Help

How to format PHP files with HTML markup in Visual Studio Code?

php laravel visual-studio-code code-formatting

I'm using Laravel so all the views are .blade.php files. Visual Studio Code won't format the HTML because of the PHP extension. I removed the blade part of the filename, but it still isn't formatti...

Jquery read query string

jquery

I'm having trouble reading a query string with Jquery. What I want to do is read the query string and based on what it says scroll to a certain place or element.