One of the most confusing things to do in a Windows application is to update your window or its controls from a background thread. Window controls will only allow updates from the main application thread. This problem existed back in the WinForms days and also within WPF.
I’ve found a real easy way though to handle this situation though which is extremely flexible to use.
Like in WinForms, you need to check if you are on the main thread or not and if not, you can use a delegate to pass information to the main thread and have it update the display. I used to create dedicated delegates and functions for updating specific controls. But I realized that you don’t need to do that if you use lambda expressions.
Here is the method that does all the work. It checks if you have access to the main thread and if so, it just executes your delegate expression. If not, it invokes the main dispatcher and passes your expression to it unaltered.
[ccle_csharp lines=”-1″ width=”600″]
public void BackgroundUpdate(Action somethingToDo)
{
if (Dispatcher.CheckAccess()) {
somethingToDo();
} else {
Dispatcher.Invoke(DispatcherPriority.Normal, somethingToDo);
}
}
[/ccle_csharp]
Now, for an example, say you have a TextBlock called myTextBlock somewhere on screen and you want to update a number on a regular basis.
[ccle_csharp lines=”-1″ width=”600″]
public void Run()
{
int count = 0;
while (count < 1000) {
int localCount = count;
BackgroundUpdate(() => {
statusBlock2.Text = string.Format(“{0}”, localCount);
});
count++;
Thread.Sleep(100);
}
}
[/ccle_csharp]
The Dispatcher being used belongs to the Window itself, so it has access to all controls within it or that it can find through other means.
One thing that is important in the example above is that tools like Resharper will complain about the variable “count” saying “Access to modified enclosure” if you tried to increase the count directly within the delegate expression and didn’t use the localCount variable. In this case, it would have still worked, but this condition can really cause headaches if you don’t understand what is happening.