C# Timer for Millisecond Waits

前端 未结 5 1386
南方客
南方客 2020-12-11 14:13

Every n*x milliseconds I perform an action where n = 0, 1, 2, ...; x is some increment.

Example - every 25 milliseconds I perform a calculation.

This action

5条回答
  •  不思量自难忘°
    2020-12-11 14:43

    At 25ms, you may be the wrong side of the resolution of your available timers in .Net.

    However - as a general solution I'd probably attempt this a different way to your "do calculation..wait until 25ms has passed" approach.

    A better way may well be to use a System.Timers.Timer, on a 25ms trigger, to trigger the calculation.

    var timer = new Timer(25);
    timer.Elapsed += (sender, eventArgs) =>
                         {
                             DoCalc();
                         };
    timer.Start();
    

    In the above example, a DoCalc method will be called every 25 ms (timer resolution issues notwithstanding). You would need to consider what to do if your calculation overran it's allotted time though. As it stands, the above code would allow a second calculation to start, even if the previous had not completed.

提交回复
热议问题