仅在完成当前迭代之后计算经过的时间,然后再进行新的迭代

时间:2014-03-22 21:51:07

标签: c# timer elapsed

我试图制作一个每5秒运行一次代码的计时器。但是这5秒只能在当前代码运行完毕后计算。

示例:

static void Main(string[] args)
{
    System.Timers.Timer timer = new System.Timers.Timer(5000);

    timer.Elapsed += (obj, ev) =>
    {
        System.IO.File.AppendAllLines(@"D:\test.txt", new string[] { DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") }, Encoding.UTF8);
        System.Threading.Thread.Sleep(3000);

        System.IO.File.AppendAllLines(@"D:\test.txt", new string[] { DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " - New" }, Encoding.UTF8);
    };

    timer.Start();

    Console.ReadLine();
}

结果:

22/03/2014 06:39:36
22/03/2014 06:39:39 - New
22/03/2014 06:39:41
22/03/2014 06:39:44 - New
22/03/2014 06:39:46
22/03/2014 06:39:49 - New
22/03/2014 06:39:51
22/03/2014 06:39:54 - New
22/03/2014 06:39:56
22/03/2014 06:39:59 - New
22/03/2014 06:40:01
22/03/2014 06:40:04 - New
22/03/2014 06:40:06

预期结果:

22/03/2014 06:39:36
22/03/2014 06:39:39 - New
22/03/2014 06:39:44
22/03/2014 06:39:47 - New
22/03/2014 06:39:52
22/03/2014 06:39:55 - New
22/03/2014 06:40:00
22/03/2014 06:40:03 - New
22/03/2014 06:40:08
22/03/2014 06:40:11 - New
22/03/2014 06:40:16
22/03/2014 06:40:19 - New
22/03/2014 06:40:24

有没有办法只计算当前事件结束后经过的时间

一件重要的事情:我可以使用的唯一类是System.Timer.Timer,我不能使用Thread.Sleep或任何类型的递归方法。

谢谢,感谢您的回答=)

1 个答案:

答案 0 :(得分:1)

也许AutoReset属性可以提供帮助。

static void Main(string[] args)
{
    System.Timers.Timer timer = new System.Timers.Timer(5000);

    timer.Elapsed += (obj, ev) =>
    {
        System.IO.File.AppendAllLines(@"D:\test.txt", new string[] { DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") }, Encoding.UTF8);
        System.Threading.Thread.Sleep(3000);

        System.IO.File.AppendAllLines(@"D:\test.txt", new string[] { DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " - New" }, Encoding.UTF8);

        //if you want to be sure it will execute, wrap the code above with try... catch
        timer.Start();
    };
    timer.AutoReset = false;
    timer.Start();

    Console.ReadLine();
}