用于在迭代之间引入1-5 ms延迟的定时器?

时间:2012-04-25 07:42:38

标签: c# timer

在我之前的问题how to suspend a thread for 1 ms?中,有人提出要引入1 ms的延迟,我应该使用Timer。

我需要“做好工作”然后平均等待2毫秒(1-5毫秒就可以,很少极端延迟可以达到几个hundreads ms),然后再次工作。重要的是不要在前一次迭代仍然没有完成时尝试启动新的迭代,所以我不需要每1-5毫秒做一些事情,我需要在迭代之间延迟1-5毫秒。

我尝试使用System.Timers.Timer执行此操作但不起作用:

using System;
using System.Diagnostics;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;

namespace TestTimer
{
    class Program
    {
        static Timer refresh_timer;
        private static int called;
        private const int ITERATIONS = 100;
        private static Stopwatch sw;

        static void Main(string[] args)
        {
            refresh_timer = new Timer(1);
            refresh_timer.AutoReset = false;
            refresh_timer.Elapsed += OnRefreshTimedEvent;
            sw = Stopwatch.StartNew();
            refresh_timer.Start();
            Thread.Sleep(10000);
        }

        static void OnRefreshTimedEvent(object source, ElapsedEventArgs args)
        {
            DoGateIteration();
        }

        private static void DoGateIteration()
        {
            //try
            //{
                // work here
                called++;
            //}
            //finally
            //{
                if (called == ITERATIONS)
                {
                    Console.WriteLine("Average iterations per second: " + ITERATIONS * 1000 / sw.ElapsedMilliseconds);
                    Console.WriteLine("Average iterations milliseconds: " + sw.ElapsedMilliseconds / ITERATIONS);
                }
                refresh_timer.Start();
            //}
        }
    }
}

报道:

Average iterations per second: 64
Average iterations milliseconds: 15

所以似乎System.Timers.Timer并不像我需要的那样精确。 可能我应该尝试System.Threading.Timer,但这个计时器没有我需要的AutoReset属性。

你会建议什么?

1 个答案:

答案 0 :(得分:0)

如果只有1或2毫秒的短暂延迟,最好只是忙碌等待:

private static int called;
private const int ITERATIONS = 10000;
private static Stopwatch sw;

static void Main(string[] args)
{
    sw = Stopwatch.StartNew();

    var x = Stopwatch.StartNew();
    while (true)
    {
        DoGateIteration();

        x.Restart();
        while (x.ElapsedMilliseconds < 2) ; // busy-wait for 2 ms
    }
}

private static void DoGateIteration()
{
    called++;
    if (called == ITERATIONS)
    {
        Console.WriteLine("Average iterations per second: " + ITERATIONS * 1000 / sw.ElapsedMilliseconds);
        Console.WriteLine("Average iterations milliseconds: " + sw.ElapsedMilliseconds / ITERATIONS);
    }
}

输出:

Average iterations per second: 500
Average iterations milliseconds: 2