JYelton
JYelton

Reputation: 36512

How to trigger a timer tick programmatically?

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?

Upvotes: 19

Views: 44615

Answers (4)

Jim Hinnant
Jim Hinnant

Reputation: 1

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.

This also allows you to trigger the code from another form using full qualification naming to the Second timer. I use this when calling from one form to another.

Upvotes: 0

Stretto
Stretto

Reputation: 486

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.

Upvotes: 9

Martin Konicek
Martin Konicek

Reputation: 40924

You could set the interval to 1 (0 probably means infinite timeout) and set it to 10k when it ticks for the first time.

The timer will tick "very soon" (depending what type of Timer you are using, see this) but the execution will not continue with the click handler as in your solution.

(I suppose you knew about the solution from Bevan).

Upvotes: 3

Bevan
Bevan

Reputation: 44307

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.

Upvotes: 40

Related Questions