Reputation: 133
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?
Upvotes: 0
Views: 963
Reputation: 401
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.
https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx
I believe you are looking at System.Timers.Timer
, which does have an Elapsed
event.
https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
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.
Upvotes: 1