Search code examples
c#for-loopstring-concatenation

Changing The Label Text in Button Click - Understanding For Loop


When I clicked button starts for loop from i=0 and I want to see on the label value of i. However I only see last values of i.

public partial class Form1 : Form
    {
        int i;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnclick_Click(object sender, EventArgs e)
        {
            for (  i = 0; i < 3; i++)
            {                
                lblForLoopExample.Text = i.ToString();
                System.Threading.Thread.Sleep(1000);
            }
        }
    }

when I run the my code I only see on the label ; 2 .

I want to see such a like below;

When the started For loop, i = 0, I must see the 0 on the Label.Text. An then when the i = 1, I must see 1 on the label.Text. And when i = 2, I must see 2 on the Label.Text.

I added Thread.Sleep(1000) however, result didn't change.

Where I am make mistake?

Please help me, if you help me , I will appreciate you.

Thanks,


Solution

  • Your problem is that you're doing work on the UI thread while expecting the UI thread to update your form.

    While you process your loop, the UI thread is actually executing this code. The UI thread is therefore unable to update the form with the intermediate values you are setting within the loop. Once your code completes, the UI thread is then free to update the form. That's why you see the last value only.

    You can see this better if you updated your code to loop ten million times instead of 3. Your form will become unresponsive and will appear locked up. That's because Windows knows your UI thread is locked in an intensive process and is unable to update the UI.

    The solution is to use a background thread to run your process and synchronize updates with the UI thread. You'll also have to slow your loop down to see the changes, as others have suggested.

    To learn more about how the UI thread works, and how to synchronize background threads with it, read this article (it's about WPF, but it covers the general case).