在其回调方法中停止计时器 [英] Stopping timer in its callback method

查看:165
本文介绍了在其回调方法中停止计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个System.Threading.Timer,每 10 ms 调用其相应的事件处理程序(回调)。该方法本身不可重入,有时可以长于10 ms 。因此,我想在方法执行期间停止计时器。

I have a System.Threading.Timer that calls its appropriate event handler (callback) every 10 ms. The method itself is not reentrant and can sometimes take way longer than 10 ms. Thus, I want to stop the timer during method execution.

代码:

private Timer _creatorTimer;

// BackgroundWorker's work
private void CreatorWork(object sender, DoWorkEventArgs e) {
      _creatorTimer = new Timer(CreatorLoop, null, 0, 10);

      // some other code that worker is doing while the timer is active
      // ...
      // ...
}

private void CreatorLoop(object state) {
      // Stop timer (prevent reentering)
      _creatorTimer.Change(Timeout.Infinite, 0);

      /*
          ... Work here
      */

      // Reenable timer
      _creatorTimer.Change(10, 0);
} 

MSDN声明回调方法被调用(每次定时器触发)单独的线程从线程池。这意味着如果我停止计时器方法的第一件事情,它仍然没有必要阻止计时器启动和运行方法的另一个实例,在第一个人有机会停止计时器之前。

MSDN states that the callback method is called (every time the timer fires) in separate thread from the thread pool. That means that if I stop the timer the first thing in method it still doesn't neccessarily prevent the timer to fire and run another instance of the method before the first one had a chance to stop the timer.

应该也许定时器(甚至不可重入方法本身)被锁定吗?
在执行回调(和不可重入)方法时,防止计时器触发的正确方法是什么?

Should maybe the timer (or even the non-reentrant method itself) be locked? What is the right way to prevent timer from firing during execution of its callback (and non-reentrant) method?

推荐答案

p>您可以让计时器继续触发回调方法,但将非可重入代码封装在Monitor.TryEnter / Exit中。在这种情况下不需要停止/重新启动定时器;重叠调用不会获取锁并立即返回。

You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately.

 private void CreatorLoop(object state) 
 {
   if (Monitor.TryEnter(lockObject))
   {
     try
     {
       // Work here
     }
     finally
     {
       Monitor.Exit(lockObject);
     }
   }
 }

这篇关于在其回调方法中停止计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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