#1,031 – Update a ProgressBar from a Background Thread

If you try to update a ProgressBar in a chunk of code that is running on the main UI thread and doing some work, the ProgressBar won’t update until all of the work is done.  In the example below, the ProgressBar won’t actually update until the loop finishes executing.

for (int i = 0; i < 100; i++)
 {
     pbTest.Value = i;
     Thread.Sleep(50);
 }

To allow the ProgressBar to update immediately, you need to do two things:

  • Do the work on a background thread
  • Periodically update the ProgressBar using a bound property (rather than directly)

We do the work on the background thread to avoid blocking the UI thread.  But we’re not allowed to update the ProgressBar from this thread because we aren’t the thread that created the control.  Instead, we update progress by setting a property that we then bind the ProgressBar.Value to.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            new Thread(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    TheProgress = i;
                    Thread.Sleep(50);
                }
            }).Start();
        }

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,031 – Update a ProgressBar from a Background Thread

  1. Pingback: Dew Drop – March 18, 2014 (#1745) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: