匿名方法作为BeginInvoke的参数? [英] Anonymous method as parameter to BeginInvoke?

查看:241
本文介绍了匿名方法作为BeginInvoke的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能将匿名方法作为参数传递给 BeginInvoke 方法?我有以下代码:

Why can't you pass an anonymous method as a parameter to the BeginInvoke method? I have the following code:

private delegate void CfgMnMnuDlg(DIServer svr);
private void ConfigureMainMenu(DIServer server,)
{
    MenuStrip mnMnu = PresenterView.MainMenu;
    if (mnMnu.InvokeRequired)
    {
        mnMnu.BeginInvoke((CfgMnMnuDlg)ConfigureMainMenu, 
                            new object[] { server});
    }
    else
    {
        // Do actual work here
    }
}

我试图避免声明委托。为什么我不能写这样的东西呢?或者我可以,我只是无法弄清楚正确的语法?以下目前生成:

I'm trying to avoid declaring the delegate. Why can't I write something like the below instead? Or can I, and I just can't figure out the correct syntax? The below currently generates an:


参数类型匿名方法不能分配给参数类型System.Delegate

Argument type 'Anonymous method' is not assignable to parameter type 'System.Delegate'

好的,当然这是正确的,但是还有一些其他语法可以用来做到这一点(避免必须声明一个单独的委托才能使用 BeginInvoke()

Ok, that's right of course, but is there some other syntax I can use to do this (avoid having to declare a separate delegate in order to use BeginInvoke()?

(能够做到这一点可以整齐地使用anon方法/ lamdas的概念代替在其他地方工作得如此干净的显式代表。)

(Being able to do this would fit in neatly with the concept of using anon methods/lamdas in place of explicit delegates which works so cleanly everywhere else.)

private void ConfigureMainMenu(DIServer server,)
{
    MenuStrip mnMnu = PresenterView.MainMenu;
    if (mnMnu.InvokeRequired)
    {
        mnMnu.BeginInvoke(  //  pass anonymous method instead ?
             delegate(DIServer svr) { ConfigureMainMenu(server);},     
             new object[] { server});
    }
    else
    {
        // Do actual work here
    }
}


推荐答案

尝试这样:

Try this:

control.BeginInvoke((MethodInvoker) delegate { /* method details */ });

或:

private void ConfigureMainMenu(DIServer server)
{
    if (control.InvokeRequired)
    {
        control.BeginInvoke(new Action<DIServer >(ConfigureMainMenu), server);
    }
    else
    {
        /* do work */
    }
}

或:

private void ConfigureMainMenu(DIServer server)
{
    MenuStrip mnMnu = PresenterView.MainMenu;
    if (mnMnu.InvokeRequired)
    {
        // Private variable
        _methodInvoker = new MethodInvoker((Action)(() => ConfigureMainMenu(server)));
        _methodInvoker.BeginInvoke(new AsyncCallback(ProcessEnded), null); // Call _methodInvoker.EndInvoke in ProcessEnded
    }
    else
    {
        /* do work */
    }
}

这篇关于匿名方法作为BeginInvoke的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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