In my last post, I talked about a hidden method on the Dispatcher associated with a WPF control to check if the current thread has access to the control. I thought that I would take a moment to explain how I actually used the CheckAccess() method.
To start with, I have a combobox in a WPF window that I would like to load a list of categories into without freezing the window itself. To load the items into the combobox, which I'd like to do at runtime, I'll use the Loaded event on the combobox.
<ComboBox Height="26" HorizontalAlignment="Left" Margin="133,0,0,3.95440729483283" Name="comboBox1" VerticalAlignment="Bottom" Width="121" Loaded="comboboxLoaded" DisplayMemberPath="Name" />
Now, I'll follow the typical pattern of calling the data access method on another thread from the comboboxLoaded method.
protected void comboboxLoaded(object sender, EventArgs e)
{
System.Threading.Thread thread = new System.Threading.Thread(Load);
thread.IsBackground = true;
thread.Start();
}
Here you'll notice I'm calling a method called Load() on a new thread. This typically would be the extent of the threading that I might do to ensure that my Load method does not hold up my UX thread. (By the way, I've grown quite fond of the term of UX (User Experience) rather than UI.) What I want to be sure of though is that the thread that I created has access to the control.
private delegate void loadCategories();
private void Load()
{
CategoryList categories = CategoryList.GetCategoryList();
if (comboBox1.Dispatcher.CheckAccess())
{
comboBox1.ItemsSource = categories;
}
else
{
comboBox1.Dispatcher.BeginInvoke(DispatcherPriority.Render,
new loadCategories(delegate
{
comboBox1.ItemsSource = categories;
}));
}
}
You'll notice that if an invoke is required, the CheckAccess() method will return false, giving me the opportunity to pass the logic off to the loadCategories delegate. This may seem a bit like overkill, but given the rich experience abilities given by WPF, the last thing that I'd want is my UI flickering or freezing up while I'm doing databinding. I think I'll explore this a bit more and build a resuable control to extend from that will auto delegate logic when necessary.