2009-09-12 97 views
2

我一直在寻找Timer类(http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx),但关于定时器的事情是,它正在进行。一旦离开后有办法阻止它吗?或5次之后?C#定时器类 - 在一定的执行次数后停止

现在我执行以下操作:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Timers; 

namespace TimerTest 
{ 
    class Program 
    { 
     private static System.Timers.Timer aTimer; 
     static void Main(string[] args) 
     { 
      DoTimer(1000, delegate 
      { 
       Console.WriteLine("testing..."); 
       aTimer.Stop(); 
       aTimer.Close(); 
      }); 
      Console.ReadLine(); 
     } 

     public static void DoTimer(double interval, ElapsedEventHandler elapseEvent) 
     { 
      aTimer = new Timer(interval); 
      aTimer.Elapsed += new ElapsedEventHandler(elapseEvent); 
      aTimer.Start(); 
     } 
    } 
} 

回答

5

它现在没有按照现在的方式进行。 Elapsed事件被提升一次并停止,因为您已经调用了Stop。无论如何,改变你的代码如下,以完成你想要的。

private static int iterations = 5; 
static void Main() 
{ 
    DoTimer(1000, iterations, (s, e) => { Console.WriteLine("testing..."); }); 
    Console.ReadLine(); 
} 

static void DoTimer(double interval, int iterations, ElapsedEventHandler handler) 
{ 
    var timer = new System.Timers.Timer(interval); 
    timer.Elapsed += handler; 
    timer.Elapsed += (s, e) => { if (--iterations <= 0) timer.Stop(); }; 
    timer.Start(); 
} 
+0

Brian,只是为了通知我纠正了代码中的错误(如果您同意,请看一下) – 2013-03-18 03:46:23

0

使用System.Threading.Timer并指定duetime参数,但指定一段Timeout.Infinite的。

+0

你好先生使用Timer对象,我已经尝试了这种方式。但它似乎使用更多的CPU,而不是我现在拥有的那个。我想我会坚持我所拥有的? – TheAJ 2009-09-12 23:26:30

0
public static void DoTimer(double interval, ElapsedEventHandler elapseEvent) 
{ 
    aTimer = new Timer(interval); 
    aTimer.Elapsed += new ElapsedEventHandler(elapseEvent); 
    aTimer.Elapsed += new ElapsedEventHandler((s, e) => ((Timer)s).Stop()); 
    aTimer.Start(); 
} 
+1

除了事实上,你在经历过两次处理时处理了什么? – codymanix 2009-09-12 23:22:21

+0

他现在可以永远不会再次启动计时器,而不会在一次间隔后停止计时 – 2009-09-12 23:27:51

+0

@cody:第二个处理程序停止计时器,以便该事件仅触发一次。这正是他所要求的。要运行五次,只需将它作为参数添加到DoTimer中即可。 lambda表达式会创建一个闭包,所以它会按预期工作。 @Yuriy:无论如何他无法重新启动该计时器:该变量对于DoTimer方法是本地的。 – 2009-09-13 01:42:08

4

你为什么不只是有一个int计数器最初开始时,在0和递增每次ElapsedEventHandler是点火时间?然后,如果计数器超过迭代次数,只需在事件处理函数中添加一个到Stop()的计时器。

0

通过创建的某一类你可以在任何类

public class timerClass 
    { 


     public timerClass() 
     { 
      System.Timers.Timer aTimer = new System.Timers.Timer(); 
      aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
      // Set the Interval to 5 seconds. 
      aTimer.Interval = 5000; 
      aTimer.Enabled = true; 
     } 

     public static void OnTimedEvent(object source, ElapsedEventArgs e) 
     { 
      Console.Writeln("Welcome to TouchMagix"); 
     } 
} 
相关问题