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.
Use a construct like this:
Be careful though to do this on the UI thread, as it will block input.
What about using the Stopwatch class.
You might as well use the
DateTime.Now.Ticks
counter: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.You can use
Stopwatch
class instead of them, like;From
TimeSpan.FromSecond