you need to tell your label to update before you do the sleep
private void button1_Click(object sender, EventArgs e)
{
label6.Text = "Working..";
label6.ForeColor = Color.Orange;
label6.Update(); // tell the label to update now
System.Threading.Thread.Sleep(1000);
label6.Text = "Finished!";
label6.ForeColor = Color.LightGreen;
label6.Update(); // tell the label to update now
}
But there is another way to do this. When you use async
and use Task.Delay()
instead of Thread.Sleep()
with your click method there is no need to call the Update()
statement.
And this also keeps your form responsive.
here is an example of how you can do this in your situation.
private async void button1_Click(object sender, EventArgs e)
{
label6.Text = "Working..";
label6.ForeColor = Color.Orange;
await System.Threading.Tasks.Task.Delay(1000);
label6.Text = "Finished!";
label6.ForeColor = Color.LightGreen;
}
So, which is better, the Update()
or the async
?
Well that depends
When you just use the Update
with Thread.Sleep()
than your form will update, as you want. But it will also not respond to anything until your Thread.Sleep()
has finished.
This can be a bad thing, but it can also be a good thing.
That depends on your situation. Maybe you don't want the users to be able to do anything at all until the Thread.Sleep()
is finished. But it also means the user cannot drag the form to some other position. That might be annoying for the user.
When you use async
and Task.Delay()
then your form will also update, as you want. But it will also respond to other actions, like dragging, resizing, clicks, etc...
If you want this, then this is the way to go.
If you dont want this, then either use the Update()
again, or make sure the user cannot click on anything he is not supposed to.
The latter is a nice solution, because the user will still be able to drag the form where he wants it whyle the operation is running, but still cannot do anything wrong.
This means that before you start the operation, disable all controls he should not be able to click on, then start the operation and when it finishes enable all these controls again.
Agreed, this is more work, but it looks much nicer for the user.
So in my opinion using the async
and Task.Delay()
is the better solution.