C#Timer Class - 在执行一定量后停止

时间:2009-09-12 23:07:42

标签: c# events timer

我一直在调查Timer类(http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx),但关于计时器的事情是,它正在进行中。有一种方法可以一次性阻止它吗?或者5点之后?

现在我正在做以下事情:

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 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:4)

为什么不只有int计数器最初从0开始,并且每次ElapsedEventHandler被触发时都会递增?然后,如果计数器超过迭代次数,您只需在事件处理程序中添加一个检查Stop()计时器。

答案 2 :(得分:0)

使用System.Threading.Timer并指定dueTime,但指定一段Timeout.Infinite。

答案 3 :(得分: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();
}

答案 4 :(得分: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");
        }
}
相关问题