Implementing a loop using a timer in C#

Raulp picture Raulp · Jul 2, 2013 · Viewed 55.4k times · Source

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

Example :

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

to

while(timer < X seconds)
{
    //do something 
}

I have two types of timers in C# .NET for this System.Timers and Threading.Timers . Which one will be better to use and how.I don't want to add extra time consumption or threading issues with the timer.

Answer

Casperah picture Casperah · Jul 2, 2013

What about using the Stopwatch class.

using System.Diagnostics;
//...
Stopwatch timer = new Stopwatch();
timer.Start();
while(timer.Elapsed.TotalSeconds < Xseconds)
{
    // do something
}
timer.Stop();