开发者

stopping a C# timer and callback executed

I am start using C# System.Threading.Timer class. When the timer is alread开发者_开发技巧y started and I am in the middle of the execution of my TimerCallback I specified, what does happen when I stop the timer using myTimer.Change(Timeout.Infinite, 0).

My callback finishes execution or it is aborted immediately?

If it is not aborted there is a way to perform something similar to Thread.Abort for the immediate killing of the code to execute?


Your callback is not aborted, it finishes execution. If you want to stop executing, simply return from the function.


I would suggest using System.Timers.Timer, and you will have to check for the Enabled property of the timer in the callback function to stop execution.

Example:

using System.Timers;

Create a new Timer object:

Timer timerObject = new Timer();
timerObject.Interval = 1000;
timerObject.Start();
timerObject.Elapsed += new ElapsedEventHandler(timerObject_Elapsed);

And in the event handlign function check for Enabled:

void timerObject_Elapsed(object sender, ElapsedEventArgs e)
{
    Timer timerObject = (Timer)sender;
    if (!timerObject.Enabled) return;
    while(true)
    {
        DoSomething.....
        if (!timerObject.Enabled) return;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜