Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sleep for 500 milliseconds

Tags:

c#

sleep

timer

Could you please tell me how do I go about pausing my program for 500 milliseconds and then continue?

I read Thread.Sleep(500) is not good as it holds up the GUI thread.

Using a timer it fires a callback ...

I just want to wait 500ms and then continue to the next statement.

Please advise.

EDIT: I need to display a status bar message for 500ms and then update the message with a different one. Sorry, I meant 500 not 50.

EDIT: I do understand what all you have said. but: [I just want to wait 500ms and then continue to the next statement.] I think because it is such a short interval i am going do a Thread.Sleep(500) on the main GUI thread. Otherwise i would have to rewrite a lot of code to accomodate this brief interval of 500 milliseconds.

EDIT: i will try to reformat my status message so the pause is not needed.

like image 850
iTEgg Avatar asked Mar 27 '10 21:03

iTEgg


1 Answers

Hmya, what you're trying to do is pretty fundamentally incompatible with the Windows programming model. A native Windows program is event driven. Your program is always idle, sitting inside a loop started by Application.Run(), waiting for Windows to tell it that something interesting happened that it should respond to. Paint requests, mouse clicks, timer expirations, stuff like that.

Your program should respond to this and filter what is interesting to you. When you drop a button on a form, you are always interested in the Click event, generated when Windows sends the MouseDown notification message. Your Click event handler runs some kind of custom code that you write. Like updating a status bar message in your case.

Updating the status bar message half a second later doesn't make a whole heckofalot of sense. What exactly happened during those 500 milliseconds that changed the way your program responds to events? You can call the Update() method of the StatusBar so the new message is visible, then call System.Threading.Thread.Sleep(500) to get what you want. You'll get away with it, the "Not Responding" ghost that Windows puts up takes your program going dead for several seconds.

But that doesn't make a lot of sense, nothing happened during that half second, the state of your program didn't change. It couldn't change, it was dead to Windows and not receiving any messages that would allow it to change state.

Well, that's about as far as I can take this. Please update your question and explain why you need to do this. Just in case: if you're contemplating this to fake doing something important for half a second, your user will not be impressed. She'll eventually notice your UI is dead for half a second without anything to show for it.

like image 114
Hans Passant Avatar answered Oct 20 '22 03:10

Hans Passant