-1

i am new to C# and I want to know why if i have a for loop inside a button handler and if i try to display the loop counter in a label , only the last value of the counter is displayed. Is there any work around this?

    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 100; i++)
        {
            this.label1.Text = Convert.ToString(i);
            Thread.Sleep(1000);
        }
    }
  • From what I remember about C#, you may have changed the text of the label, but you've not given the program time to redraw the control. Is it Refresh or Invalidate that does that? If it was Delphi, you would be missing the Application.ProcessMessages, which I think is DoEvents() in C#. – SiBrit Mar 24 '20 at 01:37
  • Your `Thread.Sleep()` makes your loop effectively a "long-running operation". You are blocking the UI thread. There are thousands of questions on Stack Overflow already addressing this type of issue. See marked duplicates for two of the most thorough examples. – Peter Duniho Mar 24 '20 at 02:17

1 Answers1

2

The Sleep method blocks the thread, which prevents the form from processing the "paint" messages that allow the screen to update.

Instead, use an async handler and Task.Delay.

private async Task button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        this.label1.Text = Convert.ToString(i);
        await Task.Delay(1000);
    }
}
John Wu
  • 50,556
  • 8
  • 44
  • 80