使用匿名方法调用WPF调度程序 [英] Invoking WPF Dispatcher with anonymous method

查看:142
本文介绍了使用匿名方法调用WPF调度程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在一个C#.Net 4.0 WPF后台线程中实现了这个不起作用(编译器错误):

  Dispatcher.Invoke(DispatcherPriority.Normal,delegate()
{
//做东西到UI
});

从一些例子中,我发现它必须像这样被转换: (Action)delegate()。然而,在其他示例中,它被转换到其他类,例如。 System.Windows.Forms.MethodInvoker



有人可以告诉我上面的例子究竟是错的吗?我也试图用其他方法重现它,但是它始终在没有投射的情况下工作:

  delegate void MyAction(); 
void Method1(MyAction a){
// do stuff
}

void Method2(Action a){
// do stuff
}

void Tests()
{
Method1(delegate()
{
// works
});

Method2(delegate()
{
// works
});

Method1(()=>
{
// works
});

Method2(()=>
{
// works
});

Method2(new Action(delegate()
{
// works
}));

new System.Threading.Thread(delegate()
{
// works
})。
}

那么调用Dispatcher的最佳(最优雅,更少冗余)的方式,那么代理人必须如此特殊地执行?

解决方案

查看 Dispatcher.Invoke() 。它不需要 Action 或其他一些特定的委托类型。它需要委托,这是所有委托类型的共同祖先。但是您不能直接将匿名方法转换为此基类型,您只能将其转换为特定的委托类型。 (同样适用于lambdas和方法组。)



为什么需要委托?因为您可以传递给具有参数或返回值的代理。



最干净的方法可能是:

  Action action = delegate()
{
//做东西到UI
};

Dispatcher.Invoke(DispatcherPriority.Normal,action);


I just realized in a C# .Net 4.0 WPF background thread that this doesn't work (compiler error):

Dispatcher.Invoke(DispatcherPriority.Normal, delegate()
{
    // do stuff to UI
});

From some examples I found out that it had to be casted like this: (Action)delegate(). However, in other examples it is casted to other classes, e.g. System.Windows.Forms.MethodInvoker.

Can anybody tell me what exactly is wrong with the example above? I also tried to reproduce it with other methods, but it was always working without casting:

delegate void MyAction();
void Method1(MyAction a) {
    // do stuff
}

void Method2(Action a) {
    // do stuff
}

void Tests()
{
    Method1(delegate()
    {
        // works
    });

    Method2(delegate()
    {
        // works
    });

    Method1(() =>
    { 
        // works
    });

    Method2(() =>
    {
        // works
    });

    Method2(new Action(delegate()
    {
        // works
    }));

    new System.Threading.Thread(delegate()
    {
        // works
    }).Start();
}

So whats the best (most elegant, less redundant) way to invoke the Dispatcher, and whats so special with it that delegates must be casted?

解决方案

Look at the signature for Dispatcher.Invoke(). It doesn't take Action or some other specific delegate type. It takes Delegate, which is the common ancestor of all delegate types. But you can't convert anonymous method to this base type directly, you can convert it only to some specific delegate type. (The same applies to lambdas and method groups.)

Why does it take Delegate? Because you can pass to it delegates that take parameters or have return values.

The cleanest way is probably:

Action action = delegate()
{
    // do stuff to UI
};

Dispatcher.Invoke(DispatcherPriority.Normal, action);

这篇关于使用匿名方法调用WPF调度程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆