Александр
Александр

Reputation: 1

Problem in my stopwatch with Thread Sleep

I wanted to make a percentage counter that will increase by 1 in 0.1 seconds, but it turns out that the program slows down completely and does not display the counter but how it became 100%

for (double percent = 1; percent <= 100; percent++)
{
    label5.Text = percent.ToString() + "%";
    Thread.Sleep(100);
}

Upvotes: 0

Views: 87

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

This is because the UI is not doing anything until the event handler is finished. Try this instead

await Task.Delay(100);

You also will have to add the async keyword to the method doing this call. Something like this:

private async void MyButton_Click(object sender, EventArgs e)

See also: Asynchronous programming (Microsoft Docs)

The linked doc says:

The await keyword is where the magic happens. It yields control to the caller of the method that performed await, and it ultimately allows a UI to be responsive or a service to be elastic.


A different approach is to use a timer. Make sure to use a timer adapted to the kind of UI you have. E.g., if you are working with winforms, use the System.Windows.Forms.Timer. You will have to add it a Tick event handler. At each tick this handler will be called on the UI thread. Update the label there (not in a loop this time!). Between two ticks, the UI will be responsive.

See also: How to: Run Procedures at Set Intervals with the Windows Forms Timer Component.
                There is a nice example doing exactly what you need.

Upvotes: 4

Related Questions