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

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

问题描述

我有一个调用其相应的事件处理程序(回调)每个 10毫秒 System.Threading.Timer。该方法本身的不能重返进入并有时需要的办法长于10毫秒。因此,我想停止方法执行过程中的定时器。

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.

code:

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指出回调方法被调用从线程池中单独的线程(定时器触发每一次)。这意味着,如果我停止计时器的第一件事就是在方法还不行neccessarily prevent计时器火灾和运行方法的另一个实例之前,第一个有机会停止计时。

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.

也许应该定时器(甚至非重入法本身)被锁定?
什么是prevent定时器以正确的方式从它的回调执行(和非折返)方法在烧制过程中?

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?

推荐答案

您可以让计时器继续射击回调方法,但包住非重入code在Monitor.TryEnter /退出键。无需停止/重新启动在这种情况下,定时器;重叠调用不会获得锁并立即返回。

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天全站免登陆