How do I get my C# program to sleep for 50 milliseconds?

Viewed 427998

How do I get my C# program to sleep (pause execution) for 50 milliseconds?

9 Answers
System.Threading.Thread.Sleep(50);

Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")

Just remove the ; to make it work for VB.net as well.

You can't specify an exact sleep time in Windows. You need a real-time OS for that. The best you can do is specify a minimum sleep time. Then it's up to the scheduler to wake up your thread after that. And never call .Sleep() on the GUI thread.

Use this code

using System.Threading;
// ...
Thread.Sleep(50);
Thread.Sleep(50);

The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.

This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.

Thread.Join

Starting with .NET Framework 4.5, you can use:

using System.Threading.Tasks;

Task.Delay(50).Wait();   // wait 50ms
Related