Home of the AlmostImplementedException

How to get responsive UIs with BackgroundWorkers

Since WPF and especially Windows 8 its obligatory to build responsive UIs. This means, the UI is always responding to an user-request even if a long taking request is made.
An easy way to achieve this is a background worker, which is nothing more then an extra thread which can work with the UI-Thread. If you don’t know why that’s so important search for it, or wait for a tutorial 😀 (little hint: only ONE process can update the user interface!).

To work with a BackgroundWorker we first need an instance of it. So we call new System.ComponentModel.BackgroundWorker(). After that we need to define a method for DoWork, which is doing the work (as you may already been guessing) and RunWorkerCompleted. Only the later (RunWorkerCompleted) can access the UI thread, which means you can’t update the UI from DoWork.
Since in DoWork all the work is done, we need to transfer values from there to the method RunWorkerCompleted. To do that, we can use DoWorkEventArgs.Result to set and RunWorkerCompletedEventArgs.Result to get values.

And finally we just have to call RunWorkerAsync() and our BackgroundWorker starts his work.
Lets have a little example:

As you can see, I use delegates to implement DoWork and RunWorkerCompleted. Its a short and clear way to do it, but you may prefer to define real functions.
In DoWork I simulate a long running database request and the results are written into args.Results. These results are transferred to the RunWorkerCompleted, which send them to our datagrid. This datagrid is only accessible from the UI Thread.
Since this example isn’t running (because of the undefined DataBase.Request), here another example:

Run this example in WPF or with windows forms.

Share :

, , , ,

Leave a Reply