简体   繁体   English

在属性Getter中使用Dispatcher.Invoke()

[英]Using Dispatcher.Invoke() in Property Getter

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. 我试图通过在getter中使用Dispatcher.Invoke()此问题,但是由于在静态上下文中无法访问非静态方法“ Invoke”,因此无法编译。

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? 有没有更简单的方法可以在WPF中使我的属性成为线程安全的?

You are using the Type Dispatcher , which doesn't have a static Invoke method. 您正在使用Type Dispatcher ,它没有静态的Invoke方法。 You need an Instance of the Dispatcher. 您需要一个调度程序Instance

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. 我假设您的View对象是DispatcherObject,它不允许从另一个线程进行访问。 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: 您可以按如下方式使用Dispatcher.CurrentDispatcher:

public override bool Enabled
{
    get
    {
        return System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(() => { return ((ISomethingView)View).ViewModel.Enabled; });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM