Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Timers: Whats is the best way to be notified in X seconds?

Suppose I have a non-recurring event that needs to be raised X seconds from now such as a timeout. Intuitively it would make sense to create a System.Timers.Timer, set its interval to X*1000, wire its tick up to the event and start it. Since this is a non-recurring event and you only want it raised once you would then have to stop the timer after it ticks.

The fact that Timers are inherently recurring however makes me distrustful if this is indeed the best way of doing it. Would it be better/more accurate/safer to save the time started, set the timer to tick every second (or even millisecond) and on tick poll the system for time and manually raise the target event only once the requisite time has elapsed?

Can anyone weigh in on which if either method is best (perhaps there is another option I didn't think of too). Does one method become better than the other if the timespan that I need to wait is measured in milliseconds?

like image 481
George Mauer Avatar asked Sep 29 '08 13:09

George Mauer


1 Answers

This constructor for the System.Threading.Timer allows you to specify a period. If you set this parameter to -1, it will disable periodic signaling and only execute once.

public Timer(
    TimerCallback callback,
    Object state,
    TimeSpan dueTime,
    TimeSpan period
)
like image 86
Ben Hoffstein Avatar answered Oct 05 '22 06:10

Ben Hoffstein