Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a timer tick programmatically?

Tags:

c#

timer

Let's say I have a Windows Forms timer configured with a 10 second (10k ms) interval:

myTimer.Interval = 10000;

I want to start it and fire off the Tick event right away:

myTimer.Start();
myTimer_Tick(null, null);

The last line works but is there a better or more appropriate way?

like image 767
JYelton Avatar asked Jan 13 '11 19:01

JYelton


People also ask

What is timer Tick?

Occurs when the specified timer interval has elapsed and the timer is enabled. public: event EventHandler ^ Tick; C# Copy.

How does the timer_tick() function work?

The timer calls it's event handlers on it's own thread, so the call the timer_Tick(null, null) here should also really be done on a background thread.

How to trigger a timer manually?

Use two timers. The First that has the normal interval you want to use and just enables the Second timer. The Second timer has an interval of 100ms and is normally disabled. It runs your code and then disables itself. To manually trigger, just enabled the Second timer.

How to implement a timer in C #?

C# Timer is used to implement a timer in C#. The Timer class in C# represents a Timer control that executes a code block at a specified interval of time repeatedly. For example, backing up a folder every 10 minutes, or writing to a log file every second. The method that needs to be executed is placed inside the event of the timer.

How to execute the timer event from the start button click?

Now write code on the Start and Stop button click handlers. As you can see from the following code, the Start button click sets the timer's Enabled property to true. Setting the timer's Enabled property starts the timer to execute the timer event.


2 Answers

The only thing I'd do differently is to move the actual Tick functionality into a separate method, so that you don't have to call the event directly.

myTimer.Start();
ProcessTick();

private void MyTimer_Tick(...)
{
    ProcessTick();
}

private void ProcessTick()
{
    ...
}

Primarily, I'd do this as direct calling of events seems to me to be a Code Smell - often it indicates spagetti structure code.

like image 158
Bevan Avatar answered Oct 16 '22 06:10

Bevan


There are at least 4 different "Timers" in .NET. Using System.Threading you can get one that specifically allows you to set the initial delay.

var Timer = new Timer(Timer_Elapsed, null, 0, 10000);

There are benefits to using the different timers and here is a good article discussing them all.

like image 31
Stretto Avatar answered Oct 16 '22 05:10

Stretto