【问题标题】:Synchronize Timer with real time实时同步定时器
【发布时间】:2020-07-11 20:21:19
【问题描述】:

我正在尝试使用timer 每隔17ms 刷新我的框架。

Timer timer = new Timer(17);
timer.Elapsed += ResetFrame;
timer.Start();

但不是等待17ms然后重复,而是等待帧刷新完成,然后等待17ms进行下一次重复。这会导致每28ms 刷新一次框架。如何实时同步?

【问题讨论】:

标签: c# winforms timer


【解决方案1】:

要拥有一个间隔很短的实时计时器,你可以看看这篇文章:

Real Time Timer in C#

在 Dot Net 中,以下计时器不是实时的。

System.Windows.Forms.Timer
System.Timers.Timer
System.Threading.Timer

表示如果你想在每 100 毫秒以上运行你的代码 计时器甚至会在 110 毫秒或之后触发。 Windows 不是真正的 因为这个.Net的时间操作系统也不是实时的。

要在 C# 中创建实时计时器,您必须编写自定义代码 可以让 CPU 在正确的时间运行您的代码。

class Program
{
   static void Main(string[] args)
  {
    Console.ReadLine();
    Console.WriteLine("Running");
    RealTimeTimerTest obj = new RealTimeTimerTest();
 
    obj.Run();
  }
}
 
public class RealTimeTimerTest
{
   List<DateTime> lst = new List<DateTime>();
  System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
 
  public void Run()
  {
    int Tick = 100;
    int Sleep = Tick - 20;
    long OldElapsedMilliseconds = 0;
    sw.Start();

    while (sw.IsRunning)
    {
      long ElapsedMilliseconds = sw.ElapsedMilliseconds;
      long mod = (ElapsedMilliseconds % Tick);

      if (OldElapsedMilliseconds != ElapsedMilliseconds && (mod == 0 || ElapsedMilliseconds > Tick))
      {

        //-----------------Do here whatever you want to do--------------Start
        lst.Add(DateTime.Now);
        //-----------------Do here whatever you want to do--------------End

        //-----------------Restart----------------Start
        OldElapsedMilliseconds = ElapsedMilliseconds;
        OldElapsedMilliseconds = 0;
        sw.Reset();
        sw.Start();
 
        System.Threading.Thread.Sleep(Sleep); 
         //-----------------Restart----------------End
      }
       
      //------------Must define some condition to break the loop here-----------Start

      if (lst.Count > 500)
      {
        Write();
        break;
      }
      //-------------Must define some condition to break the loop here-----------End
    }
  }

 
  private void Write()
  {
    System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\text.txt", true);
    foreach (DateTime dtStart in lst)
      sw.WriteLine(dtStart.ToString("HH:mm:ss.ffffff"));    sw.Close();
  }
}

还有:

Most accurate timer in .NET?

High resolution timer

High resolution timer in C#

Microsecond and Millisecond C# Timer

Precision-Repeat-Action-On-Interval-Async-Method

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多