user3723486
user3723486

Reputation: 199

Update GUI components from Begininvoke

So I have a very basic Windows Application where I want to count from 1 to 10000 and show the numbers in label:

private void button1_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(() =>
        {
            for (int i = 0; i < 10000; i++)
            {
                BeginInvoke((MethodInvoker)delegate ()
                {
                    label3.Text = i.ToString();
                });
            }
        });

        thread.Start(); 
}

The problem is that the label text doesn't update and shows only the last loop counter i.e. 9999. Is BeginInvoke called on UI thread? Why does not the label get updated correctly?

Thanks.

Upvotes: 0

Views: 460

Answers (1)

Skizz
Skizz

Reputation: 71090

Because BeginInvoke is an asynchronous call, you're sending too many updates to the text box for it to update fast enough, by the time the text box has got around to drawing, it's already counted up to 10000!

You can synchronously update the text, that is, the calling loop will halt until the text box has updated and finished, use Invoke instead of BeginInvoke.

Upvotes: 3

Related Questions