Implementing a loop using a timer in C#

后端 未结 4 1107
终归单人心
终归单人心 2021-01-11 22:23

I wanted to replace a counter based while loop with the timer based while loop in C#.

Example :

while(count < 100000)
{
   //do something 
}
         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-11 23:22

    You might as well use the DateTime.Now.Ticks counter:

    long start = DateTime.Now.Ticks;
    TimeSpan duration = TimeSpan.FromMilliseconds(1000);
    do
    {
      //
    }
    while (DateTime.Now.Ticks - start < duration);
    

    However, this seems to be something like busy waiting. That means that the loop will cause one core of your CPU to run at 100%. It will slow down other processes, speed up fans a.s.o. Although it depends on what you intend to do I would recommend to include Thread.Sleep(1) in the loop.

提交回复
热议问题