c# - 如何制作微秒计时器?

时间:2014-10-16 10:59:27

标签: c# timer

任何人都可以帮助我吗? 如何在c#中制作微秒计时器? 像其他计时器一样,我想在计时器体中做一些事情。

3 个答案:

答案 0 :(得分:3)

如果您熟悉秒表,请通过以下方式将滴答频率设置为微秒:

Stopwatch stopWatch = new Stopwatch();
stopWatch.ElapsedTicks / (Stopwatch.Frequency / (1000L*1000L));

应该解决你的问题。

答案 1 :(得分:2)

您可以在此下载MicroLibrary.cs: http://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer
问题示例:

    private int counter = 0;

    static void Main(string[] args)
    {
        Program program = new Program();

        program.MicroTimerTest();



    }



    private void MicroTimerTest()
    {

        MicroLibrary.MicroTimer microTimer = new MicroLibrary.MicroTimer();
        microTimer.MicroTimerElapsed +=
            new MicroLibrary.MicroTimer.MicroTimerElapsedEventHandler(OnTimedEvent);

        microTimer.Interval = 1000; // Call micro timer every 1000µs (1ms)
        microTimer.Enabled = true; // Start timer

        System.Threading.Thread.Sleep(2000); //do smth 2 seconds

        microTimer.Enabled = false; // Stop timer (executes asynchronously)

        Console.ReadLine();
    }

    private void OnTimedEvent(object sender,
                            MicroLibrary.MicroTimerEventArgs timerEventArgs)
    {
        // Do something every ms
        Console.WriteLine(++counter);
    }
}

}

答案 2 :(得分:0)

System.Threading.Thread.SpinWait

对于实现此“ MicroTimer”低级类目的也是必不可少的。