View Full Version : C#: Thread.Sleep(3000) executes too soon?

08-01-2009, 02:11 PM
Hey, I'm back!

I have a form with a button whose text changes right before Thread.Sleep(3000). The issue that I am having is, the sleep begins before the form button has time to update its self.

button.text = "words";
button.text = "new words";
button.text = "words";

It's actually part of a game. The button resets itself after the sleep is done, but sense the initial change doesn't occur until right before it reverts back to the way it was, it doesn't even flicker!

I hope it is just something stupid, but I get the feeling it is not...

Thanks for any and all help!

08-01-2009, 08:03 PM
That is because more than likely you are sleeping the main application thread which is responsible for repainting the form. Instead of sleeping the main thread, you should use a timer instead or create a worker thread and run your code in that.

08-02-2009, 03:33 AM
Is it possible to use a timer to pause the program?

The Thread.Sleep(3000) is in the form its self, so it would make sense that it is pausing the main thread. I don't know what kind of repercussions exist for making a new thread. Threads are a completely new concept to me.

If it is possible to use a timer, could someone please explain how I can use it to make the program wait three seconds before it continues? Or even another way.

I've looked up timers and what I have found hasn't helped one bit! I was thinking maybe a while loop, but I really just don't understand.

Thanks again for your help!

08-02-2009, 05:23 AM
The way timers work is that you set an interval and start them and they call a function of your choosing at that interval. If you only want it to happen once, you turn it off in the function when it gets called.

The exact approach to using it depends on your program, the same applies if you wanted to use a separate thread.

08-08-2009, 10:01 AM
Yeah, thanks. I did figure out how to make a timer. I don't understand why I had such a hard time with it. It wasn't very hard....

Hey, isn't there a topic solved button or something? I thought there was, but I can't find it...

08-08-2009, 06:58 PM
Edit your first post, there should be a drop down next to the thread title.