Problem
How do I get my C# program to sleep for 50 milliseconds?
This may appear to be a simple question, but I’m experiencing temporary cognitive failure as a mother.
Asked by TK.
Solution #1
System.Threading.Thread.Sleep(50);
However, keep in mind that doing so on the main GUI thread will prevent your GUI from updating (it will feel “sluggish”)
To make it work with VB.net, simply remove the ;.
Answered by Isak Savo
Solution #2
In (nearly) any computer language, there are three options for waiting:
for 1 – C# Loose Waiting:
Thread.Sleep(numberOfMilliseconds);
The windows thread scheduler, on the other hand, causes the accuracy of Sleep() to be roughly 15ms (so Sleep can easily wait for 20ms, even if scheduled to wait just for 1ms).
2. – In C#, tight waiting is:
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
//some other processing to do possible
if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
{
break;
}
}
DateTime is another option. Stopwatch is significantly faster than now or other methods of time measuring (and this would really become visible in tight loop).
for a total of three (3) – Combination:
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
//some other processing to do STILL POSSIBLE
if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
{
break;
}
Thread.Sleep(1); //so processor can rest for a while
}
This code blocks threads for 1ms (or slightly longer, depending on OS thread scheduling), thus the processor is not busy during that period and the code does not use 100% of the processor’s power. Other processing (such as refreshing the user interface, handling events, or doing interaction/communication activities) can still be done in between blocks.
Answered by Marcel Toth
Solution #3
In Windows, you can’t select a certain sleep time. For it, you’ll need a real-time operating system. The best you can do is set a minimum amount of time to sleep. After that, it’s up to the scheduler to wake up your thread. Also, don’t call. On the GUI thread, use sleep().
Answered by Joel Coehoorn
Solution #4
Since you now have async/await, utilizing Task is the best approach to sleep for 50ms. Delay:
async void foo()
{
// something
await Task.Delay(50);
}
Alternatively, if you’re targeting.NET 4 (using Async CTP 3 for Visual Studio 2010 or Microsoft.Bcl.Async), you’ll need to use:
async void foo()
{
// something
await TaskEx.Delay(50);
}
You won’t be able to block the UI thread this way.
Answered by Toni Petrina
Solution #5
Use this code
using System.Threading;
// ...
Thread.Sleep(50);
Answered by Alexander Prokofyev
Post is based on https://stackoverflow.com/questions/91108/how-do-i-get-my-c-sharp-program-to-sleep-for-50-msec