#1,031 – Update a ProgressBar from a Background Thread
March 18, 2014 1 Comment
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(); }
Pingback: Dew Drop – March 18, 2014 (#1745) | Morning Dew