I'm in a situation in which I need to do an action X ammount of times per second (refresh a PictureBox or pull bytes from socket buffer). I was wondering if there is a proper way to do this. I did some research and I found few ways of going about this.
I can work in a while loop and constantly ask OS what time is it to check if X ammount of time had passed.(DateTime.UtcNow)
I can work in a while loop and put it to sleep for a period of time.
I can work in a while loop and use Clock class to check for elapsed time.
Use Timer Class to raise event.
These are all ways I know to make something happen periodically. Second method is not very precise but I put it here for completion sake. Are there other methods I should be aware of? Which one has the least overhead?
I'm working in VisualStudio 2015 C# and version of .NET 4.6.1
Use Stopwatch, which is using high precision timer compared to DateTime.Now
DateTime.Now is good for about milliseconds precision while Stopwatch for microseconds.
// Create new stopwatch.
Stopwatch stopwatch = new Stopwatch();
// Begin timing.
stopwatch.Start();
// Do something.
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(1);
}
// Stop timing.
stopwatch.Stop();
// Write result.
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With