Karim
Karim

Reputation: 6283

what is the right way to call the Timer ElapsedEventHandler

i have a timer that calls its even handler method every 30 seconds. but i want to initialy call this method. the signature of the event handler method is

void TimerElapsed_GenerateRunTimes(object sender, System.Timers.ElapsedEventArgs e)

so how should i call it right? i can do the following

TimerElapsed_GenerateRunTimes(timerGenerateRunTimes,null);

but i am not sure this is the right way to do it besides that way the event argument e will be null

Upvotes: 1

Views: 1964

Answers (3)

Vincent McNabb
Vincent McNabb

Reputation: 34689

It would probably be best to create a separate function that does the work of the timer, and just call those. That way there will not be a mixup in the future, if you ever want to check the sender, or the event arguments in the event handler. You would also be able to know in code whether the code was manually activated, or activated from the event.

Upvotes: 0

dtb
dtb

Reputation: 217313

If you don't depend on e being not null, I don't see any problem with calling your method with null. It's your method after all, and there's nothing special about it except it matches some delegate's signature. You don't even have to pass in the timer object if you don't use sender in the method body.

(Note: If you're implementing your own class with an event, you'll always want to pass in this as sender and a non-null object for e from the method raising the event.)

Upvotes: 1

Webleeuw
Webleeuw

Reputation: 7282

At the very least pass an EventArgs.Empty object instead of null. Further, it is good practise (AFAIK) to manual call an event with the keyword 'this' as sender:

TimerElapsed_GenerateRunTimes(this, EventArgs.Empty);

Upvotes: 3

Related Questions