0

I'm trying to count up to 100 displaying the number after each addition. I want it to pause for a second between each calculation. What I get instead is a frozen program for 100 seconds with a final display of 100.

 for(int i=1; i <= 100; i++)
        {
            Thread.Sleep(1000);
            forOddOutput.Text = i.ToString();
        }
Pete Carter
  • 2,691
  • 3
  • 23
  • 34
surge
  • 3
  • 1
  • Is this Winforms or WPF or ASP.NET or something else? – mjwills Oct 22 '17 at 08:25
  • 1
    ... or [this](https://stackoverflow.com/questions/8553443/ui-not-updating-when-using-thread-sleep) or [this](https://stackoverflow.com/questions/7342075/how-can-i-update-the-ui-when-i-use-thread-sleep) or one of the many others. – Nico Schertler Oct 22 '17 at 08:26
  • I'd expect this to be as you're running on the UI thread, so the UI isn't updated until the above loop finishes. – hnefatl Oct 22 '17 at 08:26
  • 1
    @hnefatl It's the same issue, and almost exactly the same set-up (the other poster complains that he sees only the last image after a freeze; this OP says he sees only the last number after a freeze). – Sergey Kalinichenko Oct 22 '17 at 08:29

1 Answers1

1

You need to force your control to repaint - do it by using forOddOutput.Update():

for(int i=1; i <= 100; i++)
{
    Thread.Sleep(1000);
    forOddOutput.Text = i.ToString();
    forOddOutput.Update();
}
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121