【问题标题】:How Do I Pause a System.Timer in Visual Basic?如何在 Visual Basic 中暂停 System.Timer?
【发布时间】:2015-11-23 16:24:31
【问题描述】:

我在 Windows 服务中使用 system.timer 来运行通常超过计时器间隔的进程。我试图阻止计时器多次触发相同的代码,这是 system.timers 的一个已知问题。

我想要什么:计时器运行我的代码,但计时器“暂停”以等待代码完成后再恢复滴答声。

我有两个问题:

  1. system.timers 的工作方式是计时器将通过启动相同代码的新冗余线程来为您创建竞争条件,如果在计时器的时间间隔之前尚未完成,则将它们堆积在您身上已过。

  2. 我会启动/停止计时器以防止这种情况发生,但是使用 System.Timers.Timer,一旦您停止计时器以完成处理,它就永远不会回来 - 我从来没有能够计时器停止后重新启动,它已被销毁并可能被收集。启用/禁用与启动/停止完全相同,结果相同。

如果在计时器的时间间隔过去时进程还没有完成,你到底如何防止 system.timer 启动相同代码的新冗余线程?显然,启动/停止(启用/禁用)计时器不是解决方案,因为它不起作用。

救命!

【问题讨论】:

  • 尝试使用Threading.Timer。将循环时间设置为无限,仅在回调方法上重新启动计时器

标签: vb.net system.timers.timer


【解决方案1】:

在需要启动计时器时启动它,然后启动另一个线程来完成工作,之后可以停止计时器。计时器不会关心线程是完成还是带着奖金跑掉了。使用任务并行库 (TPL) 以获得最有效的使用。

【讨论】:

    【解决方案2】:

    Timer 上的 Start 和 Stop 方法确实在 Windows 服务中工作。 我有多个生产服务使用执行此操作的代码,但我的代码是用 C# 编写的。

    但是,请确保您使用的是 System.Timers.Timer不是 Windows.Forms.Timer

    这是我的服务的 C# / 伪代码的快速示例。

    // this is the OnStart() event which fires when windows svc is started
    private void OnStart()
    {
        // start your timer here.
        MainTimer.Start();
    }
    
    private void ElapsedEventHandler()
    {
          try
          { 
              // Stop the timer, first thing so the problem of another timer
              // entering this code does not occur
              MainTimer.Stop();
    
              //Do work here...   
          }
          catch (Exception ex)
          { 
              // if you need to handle any exceptions - write to log etc.
          }
          finally
          {
             MainTimer.Start();
             // finally clause always runs and will insure
             // your timer is always restarted.
          }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多