Updating the UI is a problem and it is tricky. There are very few simple rules to follow. Let’s see Here we’ll see some smart ways to perform UI updates on Console applications, Windows Forms, WPF, ASP.NET, Silverlight, Windows Phone and Windows Store apps.
Do they have UI ? No. But we’ll check how different threads perform updates on Console applications. Look at the following code. It has a main thread and another thread (worker thread) perform some time consuming task and updates the UI. Main thread shows a rotating bar till the worker thread completes.
Look at the below code. In a simple Windows Forms application, for a button click event, a time consuming task runs in a separate thread and tries to update a Label control.
When you run the above code, you will get this famous Exception. Because the Label control is created in UI thread and our worker thread tries to reach it. Cross thread referencing cannot happen as this is a violation of operating system thread handling policies. ( Do not mistake the cross thread communication and cross thread referencing, cross thread communication can happen among threads)
There are plenty of solutions for this problem, but the ready made one is to use BackgroundWorker class. The below code shows how you can use BackgroundWorker class and perform UI updates and also shows a progress bar on the UI. Events are coded inline to reduce the number of methods for this small demo.
In WPF we can use the BackgroundWorker, but also there’s a well refined solution in the WPF is to use the Dispatcher object. WPF model has Dispatcher object common across all the controls. So we can use this to update the UI.
Little modification in the PerformTask() and make it return the result.
Button click event.
Part 2 – will discuss about UI updates in ASP.NET and Silverlight.