问题描述:

I have a property which, upon access, throws an exception with the message: "The calling thread cannot access this object because a different thread owns it."

I was trying to work around it by using Dispatcher.Invoke() in the getter, but this won't compile due to `Cannot access non-static method 'Invoke' in static context.

public override bool Enabled

{

get

{

return Dispatcher.Invoke(() => (ISomethingView) View).ViewModel.Enabled;

}

}

}

Is there an easier way to make my property thread-safe from within WPF?

网友答案:

You are using the Type Dispatcher, which doesn't have a static Invoke method. You need an Instance of the Dispatcher.

Try this:

public override bool Enabled
{
  get
  {
    return Application.Current.Dispatcher.Invoke(() => (ISomethingView) View).ViewModel.Enabled;
  }
}
网友答案:

I assume your View object is the DispatcherObject which does not allow access from another thread. If so, then do something like the following:

public override bool Enabled
{
  get
  {
    return View.Dispatcher.Invoke( () => ((ISomethingView)View).ViewModel.Enabled );
  }
}
网友答案:

You can use Dispatcher.CurrentDispatcher as follows:

public override bool Enabled
{
    get
    {
        return System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(() => { return ((ISomethingView)View).ViewModel.Enabled; });
    }
}
相关阅读:
Top