Multithreaded WPF Progress Dialog
With this WPF progress dialog, you can display a progress window and invoke a method on a background thread with just a few lines of code. Let’s say, you have a worker method called CountTo100
, then all you need to get things running is this:
//create a dialog instance ProgressDialog dlg = new ProgressDialog(); dlg.Owner = this; dlg.DialogText = "hello world"; //we cannot access the user interface on the worker thread, but we //can submit an arbitrary object to the RunWorkerThread method int startValue = int.Parse(txtStartValue.Text); //start processing and submit the start value dlg.RunWorkerThread(startValue, CountTo100);
RunWorkerThread
displays the dialog as a modal window, and invokes CountTo100
on a background thread. Styling of the dialog is completely up to you, but here’s a screenshot of the dialog running in the sample application:
The dialog uses a BackgroundWorker
component and supports updating both progress bar and displayed text directly from the worker thread. Cancelling support, returning results from the worker thread and simplified exception handling are available as well. In order to get you started in no time, I’ve created a little sample application that shows a few scenarios, including parameter submission and the handling of exceptions on the worker thread. Enjoy! 🙂
Download Sample (VS2008 / VS2005 projects included): wpfprogressdialog.zip
Great Stuff! I’ve already incorporated your ideas and its working great! Thanks a lot.
That’s what i want. 😉 Sound is perfect.
Thank you Philipp 🙂
Great work! Thank you so much for sharing.
Thanks!
Works great, in few minutes I get cool looking progress 🙂
Hi Philipp, thanks so much for your suggestion about using a thread. Great example here. I tried to change your Progress Dialog example to rather update a progressBar on a statusBar of the main form but after much playing around, I’m not sure if this is even possible. Would you be able to point me in the right direction?
Many thanks!
You can invoke a local method that updates your UI from within the worker thread in the sample. Just make sure you don’t invoke it directly, but use Dispatcher.Invoke or Dispatcher.BeginInvoke. Google these methods for further information, and you should be fine 🙂
Hi,
I dont know exactly how it is working.But i tried to implement your code in my application.it is working.but after invoking the background thread again i have to use ui thread.But i get exception saying that the thread it currently owned by some other thread.Please guide me.
You would have to be more specific I’m afraid. If you want to update the UI from within the worker thread, you’ll need the Dispatcher (Dispatcher.Invoke) to perform the update.
Thanks Philipp, this was exactly what I was looking for.
Here you find another solution of a progress dialog for WPF: http://jbaurle.wordpress.com/2011/04/22/how-to-implement-a-modern-progress-dialog-for-wpf-applications/