我可以在其回调中放置Threading.Timer吗? [英] Can I dispose a Threading.Timer in its callback?

查看:48
本文介绍了我可以在其回调中放置Threading.Timer吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Threading.Timer ,例如:

new Timer(new TimerCallback(y=>
{
    try
    {
        Save(Read(DateTime.Now));
        // here i want to dispose this timer
    }
    catch
    {                          
    }
}),null,100000,10000);

我如何在回调函数中放置此计时器。或解决方法?
更新:让我解释一下情况。我想尝试调用方法保存,但会引发异常。如果可行,我需要停止计时器。

How can I dispose this timer inside of a callback. or workaround? Update: Let me explain the situation. I want to try to call the method "Save", while it throws an exception. If it works, I need to stop the timer.

推荐答案

尝试一下:

Timer timer = null;
timer = new Timer(new TimerCallback(y =>
{    
    try    
    {
        Save(Read(DateTime.Now));        
        // here i want to dispose this timer
        timer.Dispose();    
    }    
    catch    
    {    
    }
}));
timer.Change(10000, 10000);






编辑:

根据Chuu的建议,我略微更改了上面的代码。请注意,如果通过不同的计时器事件同时调用TimerCallback,则 Timer.Dispose 可能最终会被多次调用。幸运的是,计时器不在乎是否要处置多次。

I changed the above code slightly according to Chuu's suggestion. Note that if the TimerCallback is called simultanuously by different timer events, Timer.Dispose may end up being called several times. Luckily the Timer does not care if it is being disposed of several times.

这篇关于我可以在其回调中放置Threading.Timer吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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