Precision-Repeat-Action-On-Interval-Async-MethodI am trying to refresh my frame every 17ms with a timer.Timer timer = new Timer(17);timer.Elapsed += ResetFrame;timer.Start();But instead of waiting for 17ms and then repeating, it waited for the frame refresh to complete and then wait for 17msfor the next repeat. This causes the frame to be refreshed every 28ms. How to synchronize it with real time? 解决方案 To have a real time timer having a very short interval, you can take a look at this article:Real Time Timer in C#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(); }}Also that:Most accurate timer in .NET?High resolution timerHigh resolution timer in C#Microsecond and Millisecond C# TimerPrecision-Repeat-Action-On-Interval-Async-Method 这篇关于将定时器与实时同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-28 05:58