Implementing a loop using a timer in C#

后端 未结 4 1144
终归单人心
终归单人心 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:27

    Use a construct like this:

    Timer r = new System.Timers.Timer(timeout_in_ms);
    r.Elapsed += new ElapsedEventHandler(timer_Elapsed);
    r.Enabled = true;
    running = true;
    while (running) {
       // do stuff
    }
    r.Enabled = false;
    
    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
       running = false;
    }
    

    Be careful though to do this on the UI thread, as it will block input.

提交回复
热议问题