Trying to update an interface from a background thread: why does it sometimes throw and sometimes just do nothing?

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();
    //Note the use of Begin/End as opposed to the eventing model - Callback
    //will not be called on the UI thread, but a worker thread. I have
    //verified this through the debugger thread list and by checking the 
    //result of Dispatcher.CheckAccess() in the callback.
    client.BeginMyServiceMethod("MyArgument", Callback, null);
}

private void Callback(IAsyncResult result)
{
    //If I call Dispatcher.CheckAccess() here, it returns false,
    //but if I call Dispatcher.VerifyAccess() it does not throw!
    checkBox1.IsChecked = true;  // no exception, no effect
}

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?

+3
source share
2 answers

, Framework, , ? a try/catch , , . , , Framework .

+1

, GUI ( , ) . , . , "" gui , , . , tweek , , .

# wpf ( ) , :

widget.Dispatcher.BeginInvoke(delegate, args[])

, tweek , , tweek, Dispatcher (, gui).

BeginInvoke

0

All Articles