Víctor Ochoa Víctor Ochoa - 4 months ago 22
C# Question

Stopping a System.Timers.Timer

Let's say I have this code

public static Timer timer;

static void Main ()
timer = new Timer ( 60 * 1000 ); // It ticks every minute
timer.Elpased += One;
timer.Elapsed += Two;

private static void One ( sender o, EventArgs e )
timer.Stop ();

private static void Two ( sender o, EventArgs e )
DoSomething ();

Since I'm assuming that 'One' and 'Two' will execute in subscribe order, stopping the Timer in 'One' will prevent 'Two' from happening?

If not, how can I do it?


System.Threading.Timer does not have an Elapsed event. It requires a single TimerCallback delegate passed to the constructor, which it executes on a ThreadPool thread.


I believe you are looking at System.Timers.Timer, which does have an Elapsed event.


I do not believe there is a way to guarantee a way to prevent Two from firing the way you describe. You must assume that One and Two execute at the exact same time on 2 different threads. Even calling Stop() isn't guaranteed to prevent the timer from firing an additional time: https://msdn.microsoft.com/en-us/library/system.timers.timer.stop(v=vs.110).aspx.

My suggestion would be to have a single callback that handles the branching logic on if it should perform the actions in Two after the logic in One executes.