0

在我之前的问题中,如何将线程挂起 1 毫秒?有人回答说要引入 1 毫秒的延迟,我应该使用定时器。

我需要“工作”然后平均等待 2 毫秒(1-5 毫秒是可以的,很少有极端延迟到几百毫秒是可以的),然后再次工作。重要的是不要在上一次迭代仍未完成时尝试开始新的迭代,所以我不需要每 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我需要的属性。

你有什么建议?

4

1 回答 1

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);
    }
}

输出:

每秒平均迭代次数:500
平均迭代毫秒数:2
于 2012-04-25T07:52:15.320 回答