Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire timer.Elapsed event immediately

Tags:

c#

events

timer

I'm using the System.Timers.Timer class to create a timer with an Timer.Elapsed event. The thing is the Timer.Elapsed event is fired for the first time only after the interval time has passed.

Is there a way to raise the Timer.Elapsed event right after starting the timer ?

I couldn't find any relevant property in the System.Timers.Timer class.

like image 470
Otiel Avatar asked Aug 03 '11 09:08

Otiel


People also ask

How do I stop a timer elapsed event?

It would have already queued before you have called Stop method. It will fire at the elapsed time. To avoid this happening set Timer. AutoReset to false and start the timer back in the elapsed handler if you need one.

What is timer Elapsed event in Windows service?

Elapsed event every two seconds (2000 milliseconds), sets up an event handler for the event, and starts the timer. The event handler displays the value of the ElapsedEventArgs. SignalTime property each time it is raised.

What does timer elapsed mean?

Elapsed time is the amount of time that passes from the start of an event to its finish. In simplest terms, elapsed time is how much time goes by from one time (say 3:35pm) to another (6:20pm).


2 Answers

Just call the Timer_Tick method yourself.


If you don't want to deal with the Tick callback method's parameters, then just put the code that was in your Timer_Tick into another method, and call that from the Timer_Tick and from just after the Timer.Start() call


As pointed out by @Yahia, you could also use the System.Threading.Timer timer, which you can set to have an initial delay to 0. Be aware though, that the callback will run on a different thread, as opposed to the callback on the Windows.Forms.Timer which runs on the UI thread. So if you update any UI controls using the System.Threading.Timer (without invoking correctly) it'll crash.

like image 131
George Duckett Avatar answered Sep 20 '22 05:09

George Duckett


I just called the **ElapsedEventHandler** with null parameters.

like image 29
user1791983 Avatar answered Sep 18 '22 05:09

user1791983