Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the impact of Thread.Sleep(1) in C#?

In a windows form application what is the impact of calling Thread.Sleep(1) as illustrated in the following code:

public Constructor() {     Thread thread = new Thread(Task);     thread.IsBackground = true;     thread.Start(); }  private void Task() {     while (true)     {         // do something         Thread.Sleep(1);     } } 

Will this thread hog all of the available CPU?

What profiling techniques can I use to measure this Thread's CPU usage ( other than task manager )?

like image 322
Justin Tanner Avatar asked Feb 03 '09 17:02

Justin Tanner


People also ask

What happens when thread sleeps?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Does thread sleep consume CPU?

To be more clear: Threads consume no CPU at all while in not runnable state. Not even a tiny bit. This does not depend on implementation.

What is the problem with thread sleep in code?

When using Thread. sleep(), we have to mention wait time in advance, there is no guarantee that the element will be displayed in that specific wait time, there may be case when it will takes may be more than 5 seconds to load and again the script would fail.

Does thread blocking sleep?

Sleep method. Calling the Thread. Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution.


1 Answers

As stated, your loop will not hog the CPU.

But beware: Windows is not a real-time OS, so you will not get 1000 wakes per second from Thread.Sleep(1). If you haven't used timeBeginPeriod to set your minimum resolution you'll wake about every 15 ms. Even after you've set the minimum resolution to 1 ms, you'll still only wake up every 3-4 ms.

In order to get millisecond level timer granularity you have to use the Win32 multimedia timer (C# wrapper).

like image 83
Bob Nadler Avatar answered Oct 13 '22 16:10

Bob Nadler