简体   繁体   English

从WPF ui线程混淆访问委托

[英]Confused accessing delegate from WPF ui thread

My apologies but I can't see what I am doing wrong / not understanding? 抱歉,我看不到自己在做什么错/无法理解? I have declared a delegate such as: 我已经声明了一个代表,例如:

namespace ABC
{
   public delegate void GenerateView();

   public class X
   {
      public X()
      {
         GenerateView handler = GenerateViewMethod;
      }

      public void GenerateViewMethod()
      { .... }

    }
 }

Then in the ui I call it as such: 然后在用户界面中这样称呼它:

private readonly X MyXClass;
Dispatcher.BeginInvoke(MyXClass.???) //handler isn't an option?

The only method that shows is GenerateViewMethod and of course that isn't my delegate. 显示的唯一方法是GenerateViewMethod,当然不是我的委托。

So obviously I am not exposing the delegate properly but I'm not clicking on what is missing. 因此很明显,我没有适当地公开代表,但是我没有点击缺少的东西。

Thank you for the assistance 感谢您的帮助


Update further information 更新更多信息

I have a WPF Ui and when the user clicks the only button I simply want to do some processing in a different thread and not lock the ui. 我有一个WPF Ui,当用户单击唯一的按钮时,我只是想在其他线程中进行一些处理而不锁定ui。 Pretty simple little test for me as I'm learning. 我正在学习的时候,对我来说是非常简单的小测试。

The reason your current code doesn't work is that handler is just a local variable within the constructor. 您当前的代码不起作用的原因是handler只是构造handler中的局部变量。

While you could add a public property, if the point is just for external code to be able to get a delegate which calls GenerateViewMethod , you don't need anything extra for that - the other code can just use a method group conversion. 尽管可以添加一个公共属性,但是如果仅是为了使外部代码能够获得调用GenerateViewMethod的委托,则不需要额外的操作,其他代码仅可以使用方法组转换。 For example: 例如:

Action action = MyXClass.GenerateViewMethod;
Dispatcher.BeginInvoke(action);

Or: 要么:

Dispatcher.BeginInvoke((Action) MyXClass.GenerateViewMethod);

Or if you're using DispatcherExtensions , you can simply use: 或者,如果您正在使用DispatcherExtensions ,则可以简单地使用:

Dispatcher.BeginInvoke(MyXClass.GenerateViewMethod);

The reason the DispatcherExtensions class helps here is that the methods declared by Dispatcher itself only take Delegate parameters, so the compiler needs to be told what kind of delegate to build. 究其原因, DispatcherExtensions类可以帮助这里是通过声明的方式Dispatcher本身只能采取Delegate参数,所以编译器需要被告知要建设什么样的委托。 The extensions take the specific Action delegate, so the compiler just converts the method group to that. 这些扩展采用特定的Action委托,因此编译器仅将方法组转换为该委托。

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

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