Implementing a loop using a timer in C #

I would like to replace the counter based loop with the timer based 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 these System.Timers and Threading.Timers . Which one is better to use and how. I do not want to add extra time or problems with the stream using a timer.

+4
source share
4 answers

Use the construct as follows:

 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 if you do this in the user interface thread, as it will block input.

+6
source

How about using a stopwatch class.

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

You can use the Stopwatch class, for example:

Provides a set of methods and properties that you can use to accurately measure elapsed time.

 Stopwatch sw = new Stopwatch(); sw.Start(); while (sw.Elapsed < TimeSpan.FromSeconds(X seconds)) { //do something } 

From TimeSpan.FromSecond

Returns a TimeSpan that represents the specified number of seconds where the specification is accurate to the nearest millisecond.

+4
source

You can also 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 like an expectation. This means that the cycle will make one core of your processor work 100%. This will slow down other processes, speed up aso fans. Although it depends on what you intend to do, I would recommend including Thread.Sleep(1) in the loop.

0
source

Source: https://habr.com/ru/post/1489214/


All Articles