I think everyone is guilty of this to an extent. How often do you execute code that ‘could’ take a long time to execute, under the UI thread? The end-user presses a button, your code does it stuff, in the meantime the UI is, well, hung! Sometimes it’s almost unnoticeable, a quick 500ms pause – But that code still shouldn’t be in there. Because hangs can be minor, they will sometimes go unnoticed.
I thought I’d write a quick example of the right and wrong ways of dealing with code triggered from the UI thread. At the bottom of the post is a Visual Studio 2010 Project which demonstrates this. You will have to excuse my obsession with delegates!
First of all, I’m going to define a private ‘Thread’ which is going to handle my background work (Line 5):
1: // Author: Mike Lovell (email@example.com)
3: public partial class MainWindow : Window
5: private Thread workerThread;
8: public MainWindow()
In this WPF project, I have two buttons to demonstrate each method of doing things, called ‘buttonStartRight’ and ‘buttonStartWrong’. Lets just make a little function to allow us to enable/disable them both at the same time
14: private void SetButtonsIsEnabled(bool value)
16: buttonStartRight.IsEnabled = value;
17: buttonStartWrong.IsEnabled = value;
Okay, now the wrong way to do it!
21: private void buttonStartWrong_Click(object sender, RoutedEventArgs e)
25: for (int i=0; i<100; i+= 10)
29: progress.Value = (double)i;
Although it may appear that this code will run nicely, it won’t (try it). What will happen? Nothing, until the entire function ’buttonStartWrong_Click’ has completed. The progress bar WON’T be updated at each step, the buttons WON’T have ‘isEnabled’ set to false (from our function call on Line 21).
You’ll click the button, the UI thread will be blocked (the button won’t even pop up again indicating it’s clicked). It’s a good old fashion hang (Ah, those VB6 days!).
So what is the right way? Lets use that ‘Thread’ we declared earlier for this function:
36: private void buttonStartRight_Click(object sender, RoutedEventArgs e)
40: workerThread = new Thread(new ThreadStart(delegate()
42: for (int i=0; i<100; i+= 10)
48: progress.Value = (double)i;
49: }, null);
55: }, null);
So I’ve created an instance of a‘Thread’ with an anonymous delegate containing the code I want to run (Line 40). As I’m now in a different thread from the UI, I won’t be allowed to directly work with its controls. I need to use the ‘Dispatcher’ to talk to the UI thread. I’ve made anonymous delegates for each of my calls back to the UI thread to make updates (to both the progress bar on Line 46, and the buttons on line 52).
Some other bloggers covering multi-threading in WPF: