可靠停止System.Threading.Timer? [英] Reliably stop System.Threading.Timer?

查看:377
本文介绍了可靠停止System.Threading.Timer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我已经搜索了很多的解决了这一点。我是从我已经停止后,被调用寻找一个干净和简单的方法prevent一个System.Threading.Timer的回调方法。

Well I've searched a lot for a solution to this. I'm looking for a clean and simple way to prevent the callback method of a System.Threading.Timer from being invoked after I've stopped it.

我似乎无法找到任何,而这也导致了我,就occassion,诉诸可怕的线程的Thread.Sleep-Thread.Abort的组合的不寒而栗

I can't seem to find any, and this has led me, on occassion, to resort to the dreaded thread-thread.sleep-thread.abort combo shudders.

可以使用它锁做?请帮我找到一个很好的办法做到这一点。谢谢

Can it be done using lock? Please help me find a good way to do this. Thanks

推荐答案

康拉德Frix 建议你应该使用 System.Timers.Timer 类代替,如:

like Conrad Frix suggested you should use the System.Timers.Timer class instead, like:

private System.Timers.Timer _timer = new System.Timers.Timer();
private volatile bool _requestStop = false;

public constructor()
{
    _timer.Interval = 100;
    _timer.Elapsed += OnTimerElapsed;
    _timer.AutoReset = false;
    _timer.Start();
}

private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    // do work....
    if (!_requestStop)
    {
        _timer.Start();//restart the timer
    }
}

private void Stop()
{
    _requestStop = true;
    _timer.Stop();
}

private void Start()
{
    _requestStop = false;
    _timer.Start();
}

这篇关于可靠停止System.Threading.Timer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆