Reputation: 133
I'm working on a small C# Windows Form application. In this application, I've used Thread.Sleep to wait on the current screen before moving to the next one. The problem is that before the Thread.Sleep line, I've changed the color of some of the buttons. What's weird is that it doesn't show that the color of the buttons changed. Just like it imedietly skips to the Threat.Sleep line.
That's the code that causes the problem:
for(int i = 0; i < Buttons.Count; i++)
{
if(Buttons[i].Text == currentCard.rightAnswer)
{
Buttons[i].BackColor = Color.Green;
}
else
{
Buttons[i].BackColor = Color.Red;
}
}
lbl_correctOrWrong.Visible = true;
if(btn.Text == currentCard.rightAnswer)
{
lbl_correctOrWrong.ForeColor = Color.Green;
lbl_correctOrWrong.Text = "Currect!";
}
else
{
lbl_correctOrWrong.ForeColor = Color.Red;
lbl_correctOrWrong.Text = "Wrong!";
}
Thread.Sleep(1500);
MoveToNextQuestion();
Any help would be much appreciated, thanks!
Upvotes: 0
Views: 58
Reputation: 29009
All the UI activities in a WinForms application happen by default on the main thread (also called the UI thread because of that).
When you use a statement like:
Buttons[i].BackColor = Color.Green;
It actually sends a message to the control to change it's color. As all the rest of the UI code, this message execution is done also on the main (UI) thread. The main thread's top level is actually a message loop - extracting UI messages from a Q and executing them.
The problem is that when you use something like:
Thread.Sleep(1500);
And you are on the UI thread, the message loop cannot continue because the thread is sleeping.
The result is that the color changes only after the main thread completes the sleep, and resumes the message handling.
Bottom line: you should avoid using sleep on the main thread. You can use a timer to do some operation after some time has passed.
Upvotes: 3