C#Timer Class - 在执行一定数量的操作后停止

The*_*eAJ 2 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*eon 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();
}
Run Code Online (Sandbox Code Playgroud)