Rohan
Rohan

Reputation: 1805

Textbox not getting updated in for loop

I have a for loop in my WPF. The textbox does not get updated until the loop has finished.

My code:

for (int i = 0; i < 10; i++)
{
    Thread.Sleep(1500);
    // MessageBox.Show(i.ToString());
    updateTextBox(i);
}

Update function:

private void updateTextBox(int i)
{
    // MessageBox.Show("reached here:" + i.ToString());
    txtExecLog.AppendText("\n" + i.ToString());
 }

If I uncomment the messagebox text, it updates one by one, otherwise it updates after 15 secs (1.5*10) the textbox with all the values.

Upvotes: 0

Views: 1182

Answers (2)

Fischermaen
Fischermaen

Reputation: 12458

You are running your loop in the UI thread. When you call Thread.Sleep() the UI thread sleeps and therefore the textbox can't be updated before end of the UI thread blocking for loop.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500515

You're blocking the UI thread when you sleep. You mustn't do that - nothing can be processed on the UI thread while you're sleeping. If you want to take an action periodically (on the UI thread) use DispatcherTimer.

Upvotes: 2

Related Questions