Answered by:
How to replace Thread.Sleep(Int32)

Question
-
I really liked using Thread.Sleep() to pause my application because it was very easy to use.
It doesn't seem to be working now, there is no Sleep() method.
So how can we replace Thread.Sleep() to pause the app for X milliseconds?
Sunday, October 9, 2011 2:16 PM
Answers
-
Hi Okh2,
To asynchronously delay for two seconds do the following:
await Task.Delay(2000);
The await operator is designed to make asynchronous patterns much less complicated as the compiler can hook up all of the callbacks for you.
Using Sleep() to block the UI thread for several seconds makes the UI unresponsive and is a large source frustration for users. Asynchronous patterns help keep the UI running seamlessly.
See http://msdn.microsoft.com/en-us/library/windows/apps/hh452713(v=VS.85).aspx for a good overview on async in C# and WinRT
There are also several //build/ sessions you might want to watch on async:
Async everywhere: creating responsive APIs & apps: http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-203T
The zen of async: Best practices for best performance: http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-829T
--Rob- Marked as answer by Rob Caplan [MSFT]Microsoft employee, Moderator Monday, October 17, 2011 1:07 AM
Monday, October 10, 2011 7:40 PMModerator
All replies
-
Thread.Sleep isn't a particularly good design pattern in applications, it almost always indicates a situation in which a delay is being inserted either in the hope something completes (rather than specifically waiting for it to complete) or simply to try and bodge a fix for a race condition. Removing it encourages developers to use an appropriate asynchronous pattern for the task they're trying to accomplish.
If you give a better idea of what it is you are trying to do by sleeping, a more appropriate solution could be suggested.
Sunday, October 9, 2011 6:31 PM -
@AndyAdley
Design patterns for Thread.Sleep()??? LOL.
Sunday, October 9, 2011 8:18 PM -
There is a timer in WinRT
http://msdn.microsoft.com/en-us/library/windows/apps/windows.system.threading.threadpooltimer.createtimer%28v=VS.85%29.aspx
Hopefully you can figure how to make callback report into your code. Or wait for a better answer.
Sunday, October 9, 2011 8:24 PM -
Yes, as in code which uses Sleep usually follows a pattern along the lines of:
start a long-running operation while ( not finished ) { Thread.Sleep (100) }
which is periodically polling the result. This is an anti-pattern which results in unecessarily waking of the process and blocking the thread until a result is available. It's far better to use asyncronous code, that keeps the thread free and doesn't result in the process being scheduled until such time that the code can actually continue to execute, regardless of how long that is.Sunday, October 9, 2011 10:34 PM -
Do you seriously believe that there is only one application for Thread.Sleep()? And that is to block and poll?
More importantly, whoever suggested to kick Thread.Sleep(), or its alternative Task.Delay() from WinRT (or .NET 4.5) is in my mind a (useless) bookworm.
- Edited by SLx64 Monday, October 10, 2011 1:42 PM
Monday, October 10, 2011 1:57 AM -
Yeah, I know Thread.Sleep() isn't so good, but it is really simple to use instead of a complicated asynchronous pattern.
One application of Thread.Sleep() is the one you talked, but I wouldn't use Thread.Sleep in that situation. Instead, in my situation, the user acts (that is he taps a button) and the computer has to answer to that action. However in my situation an instant answer, which is the one the computer gives, is not nice. So I need a method to delay computer's answer by some seconds, just because it's nicer this way. I don't know if I explained my situation well.- Edited by okh2 Monday, October 10, 2011 2:45 PM
Monday, October 10, 2011 2:45 PM -
Hi Okh2,
To asynchronously delay for two seconds do the following:
await Task.Delay(2000);
The await operator is designed to make asynchronous patterns much less complicated as the compiler can hook up all of the callbacks for you.
Using Sleep() to block the UI thread for several seconds makes the UI unresponsive and is a large source frustration for users. Asynchronous patterns help keep the UI running seamlessly.
See http://msdn.microsoft.com/en-us/library/windows/apps/hh452713(v=VS.85).aspx for a good overview on async in C# and WinRT
There are also several //build/ sessions you might want to watch on async:
Async everywhere: creating responsive APIs & apps: http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-203T
The zen of async: Best practices for best performance: http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-829T
--Rob- Marked as answer by Rob Caplan [MSFT]Microsoft employee, Moderator Monday, October 17, 2011 1:07 AM
Monday, October 10, 2011 7:40 PMModerator -
Hi Rob,
Why is it someones business how the developer screws his UI?
If Microsoft is so worried about grandmas not seeing pictures of their puppies animate, don't let devs touch UI threads altogether. Make it standard to update controls through Dispatcher. Let them draw and animate into backbuffers. Whatever.
But taking away Thread.Sleep() is silly for that reason.
Monday, October 10, 2011 8:40 PM -
Hi Rob,
Why is it someones business how the developer screws his UI?
Because when it happens people say "Stupid Windows, it makes applications freeze when I'm trying to work with them".Modern development technology makes asyncronous programming extremely easy, so there is just no reason to provide APIs that make users feel their applications aren't responsive.
Monday, October 10, 2011 8:52 PM -
I use Thread.Sleep() TO HELP me debug my code. And when I do that I don't give rat's @ss about any "applications aren't responsive" crap.
Sorry for rudeness, but it has to be said.
To rephrase you, there is just no reason to NOT provide APIs that help devs create better user experience.
Thanks.
Monday, October 10, 2011 9:04 PM -
static void Sleep(int ms) { new System.Threading.ManualResetEvent(false).WaitOne(ms); }
- Proposed as answer by dpittman1 Tuesday, February 14, 2012 8:05 PM
Tuesday, February 14, 2012 8:02 PM -
For the C++ fans (using sanctioned APIs):
static void Schleep(uint32 ms) { WaitForSingleObjectEx(GetCurrentThread(), ms, FALSE); }
For the assembly fans:
push 0 push ms call GetCurrentThread push eax call WaitForSingleObjectEx
;)
- Proposed as answer by evangineer Wednesday, March 7, 2012 9:46 PM
Wednesday, March 7, 2012 9:46 PM -
From Sleep documentation
"A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution."
Will these code archive the same:
WaitForSingleObjectEx(GetCurrentThread(), 0, FALSE);
Wednesday, May 2, 2012 4:31 PM -
how do you think network packet collisions are handled?. the colliding parties wait for a random interval before using the bus again. sleep is an extremely important programming concept not limited to async programming. another example is a server that is too busy and a client that must wait a few seconds before attempting another request.
thread.sleep is neither bad nor good any more than a while or for loop is bad or good.
Friday, September 14, 2012 12:57 AM -
You can actually pause your application by using Task.Delay()
And the code is
public async void pause_ButtonClick_Handler()
{
await Task.Delay(int milliseconds);
}
- Proposed as answer by pradeepreddy001 Saturday, March 30, 2013 4:53 AM
Saturday, March 30, 2013 4:53 AM -
Since the System.Threading.ManualResetEvent implements the IDisposable interface, should we not dispose of it?
Public Shared Sub Sleep(ByVal duration As TimeSpan) Using sleeper = New System.Threading.ManualResetEvent(False) sleeper.WaitOne(duration) End Using End Sub
public static void Sleep(TimeSpan duration) { using (var sleeper = new System.Threading.ManualResetEvent(false)) { sleeper.WaitOne(duration); } }
- Edited by Randy Dodson Tuesday, April 2, 2013 2:56 PM
Tuesday, April 2, 2013 2:54 PM