Technology blog written by a Microsoft C# MVP

C# WPF: Threading, Control Updating, Status Bar and Cancel Operations Example All In One

Jul 212010

Bringing them together; this article shows how to do GUI processing and background work in WPF using C# with an eye on progress and the ability to cancel. This article demonstrates all these topics :

Create a background thread to do work away from GUI as to not slow down the user experience.

Pass data from the GUI thread to the background worker and subsequently to GUI to update appropriate controls.

Safely update screen data after work is done.

Invoke/Dispatch back to control GUI thread from worker as needed.

Associate threaded work with progress bar in WPF to provide status.

Allow the users to stop or cancel the process and handle it appropriately.

Enable and disable buttons so user is not kicking off superfluous actions while the work process is executing.

I write these articles to enlighten the development community as well as notes for myself as I work in the differing technologies going forward. For this article I saw many websites which would individually piece these topics together, but none of them showed the the whole process. This article covers the whole process.

BackgroundWorker Not Just For Winforms Anymore

The goal of the operation is to do the work, and that work is not done on the GUI thread where a user will notice the slow down, but on a background thread. To accomplish that, one of the best fixtures of .Net is the Background thread which was introduced for Winforms. Even though the BackgroundWorker is a nice drag and droppable component in the Winform arena it does not mean that it can’t moonlight in our WPF sandbox. We simply have to instantiate and initialize it ourselves. Here is the code to do that in our Window class:

Line 3: We must declare and subsequently instantiate a background worker which will be used. This object and operations can be reused so this only needs to be done once and to keep temporality we declare it on the window class itself.

Line 9/10: We are subscribing to the events which will handle our work on the separate thread. The DoWork event is where the heavy lifting of the offloaded operations will occur. The RunWorkerCompleted event is the safe haven where we can pipe the results of DoWork to the GUI controls without having to invoke or dispatch back to the controls because the event code will be done on the GUI’s thread. Note intellisense is our friend one these lines. Type in += and intellisense offers to create the subscribing to the event handler with a Tab. A subsequent Tab key will create the method stub. Give it a try.

Line 12/13: Here is where we tell the background worker that we are going to do a progress operation back to the GUI for the user experience. Note if we don’t specify WorkReportsProgress we will get this exception:This BackgroundWorker states that it doesn’t report progress. Modify WorkerReportsProgress to state that it does report progress.

Line 15: Here is where we also inform the BackgroundWorker object that we will be handling cancellation.

Xaml Mammal

With the goal of providing a cancel and progress status bar as such:

Here is the code to add to our Xaml where it lives at the bottom of our screen. Below the code is the status bar and its child elements of a TextBlock, ProgessBar and button for the cancel.

The only thing to note that initially the Cancel button and progress bar visibility is set to hidden.

Launching the Operation from a Button Click

Here is the code where we launch the DoWork event operation, but more importantly we pass in data which the DoWork can use to perform its operations. The data here is special because it all resides on gui controls. We don’t want to access that data directly from our worker thread otherwise we will get this exception as reported in my previous article (C# WPF: Linq Fails in BackgroundWorker DoWork Event ) :

The calling thread cannot access this object because a different thread owns it.

The first thing we do is darken the button which launched the process so the user doesn’t click it twice. Then we make the cancel button and the progress bar visible to the user as the process is about to begin. Finally we extract data held in Gui controls exposed to the user. We cannot access that data once the thread is running and must get the data to to the DoWork process.

Is It Done Yet? Move the Progress Bar.

Here is our event which handles the moving of the progress bar. This is done on the GUI thread so no need to do checking of the dispatch. We get a numeric percentage which moves the bar along and incremental movements.

Cancelling the Operation from a Button Click

The cancel is similar because we do the opposite of the initiation code above by hiding the controls and informing the user of the stop action. This cancel is initiated by the cancel button on click event shown in the Xaml above. We do all this on the cancel because a cancel event does not fire the RunWorkerCompleted event.;

Line 5: We will return Results to the RunWorkerCompleted event and this line initializes it.

Line 7: This method was passed data. Here is where we unbox our present which is a Dictionary which contains our user input we are interested in processing.

Line 11: Here is where we pass our percentage. It will move the bar up 33 percent. You can dictate what percentage of the process is done. I have chosen 33 in this case, because the code does three separate work items and it will allow for a smother transitions.

Line 16 : Here is where we access the passed in dictionary which holds our user inputs.

Line 22: The first work unit will be executed on this line and the database call will be made. After this line we can bump up the progress bar.

Line 24: Our first important check to see if the user wants to cancel. If a cancel event has been fired, we simply exit this method. Cancellation means that the follow up function RunWorkerCompleted will not be fired.

Line 27: If we are here, bump up the progress bar.

Line 28-37: Repeat of the work, check cancel and move progress bar as shown above. Though once done, we bump the result to 100%! We are done with the work.

Line 39: Now we place the results on the DoWorkEvents Result property to be used in the RunWorkerCompleted.

Line 44: The exception actually reports the error to in this case a List box named lbxData. This is accomplished by using the controls Dispatcher invoke code. That invoke ensures that the action against the control is done safely on the GUI thread. We could have used this in our code instead of putting things onto a result. But I have chosen not to because if the user cancels, we don’t have half loaded data to unload from controls. By passing the result to the RunWorkerCompleted event we ensure that all data is properly populated and no complex back out of data during error situations is needed. But since this is a exceptional and unplanned situation, I have chosen to write to the control directly. You have the tools to do either, its your design. 🙂

Time to Display the Result to the User

Finally our work is done and all is complete. The below code safely writes the result to the GUI thread’s controls.

Yes that is by design of the Worker. In the do work event, it needs to periodically check for the cancel scenario and stop if it sees one. When it sees a cancel it needs to stop working and set a flag so the Runworker completed knows that a cancel has happened:

You, sir, have saved me a great deal of time and headaches. Thanks for this!

I had written a class that did the work and updated the progress bar and status, but it wasn’t working as I expected. It only took a slight modification to make it work the way you described above. I tried passing a reference to the window so I could update the status bar from the class doing the work, but couldn’t do that because it was owned by a different thread. Not a big deal; I’m sure that there’s a way to signal that other thread, but for what I’m doing, it’s not required. 🙂

WOW – thank you for this. I’d been looking all over for some straight forward code on making operations happen in the background. I really appreciated this. As Daniel said, you’ve saved me a lot of time and possibly headache!