0

我试图制作一个每 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 或任何类型的递归方法。

谢谢,我很感激你的回答=)

4

1 回答 1

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();
}
于 2014-03-22T22:01:55.577 回答