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 )?
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.
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.
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.
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.
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).
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