简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM