I noticed in WPF that when I try to update the user interface from a background thread (I know that you shouldn't do this just by playing things), that sometimes it throws an InvalidOperationException, and sometimes it just doesn't do anything. I first noticed this when I incorrectly tried to update the user interface from a background thread started by calling async WCF (using Begin / End rather than the calling model, which automatically marchs to the user interface thread).
For example, let's say I have a simple form with a button and a checkbox. This code will raise an InvalidOperationException ("the calling thread cannot access this object because another thread belongs to it") each time:
private void button1_Click(object sender, RoutedEventArgs e)
{
new Thread(() => checkBox1.IsChecked = true).Start();
}
Now, take the same form and add a link to the bog-standard service for a simple WCF service. Then try the following:
private void button1_Click(object sender, RoutedEventArgs e)
{
var client = new MyServiceClient();
client.BeginMyServiceMethod("MyArgument", Callback, null);
}
private void Callback(IAsyncResult result)
{
checkBox1.IsChecked = true;
}
I understand that the call to Dispatcher.VerifyAccess () in this callback method should be thrown, just like when trying to manipulate something on checkBox1. Instead, nothing happens - a flag in the user interface is not checked, and an exception is not thrown. Does anyone know why this is so?
source
share