C# 匿名方法作为 BeginInvoke 的参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1007438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:22:46  来源:igfitidea点击:

Anonymous method as parameter to BeginInvoke?

c#delegatesanonymous-methodsbegininvoke

提问by Charles Bretana

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

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

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:

我试图避免声明委托。为什么我不能写类似下面的东西呢?或者我可以,我只是想不出正确的语法?以下当前生成一个:

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

参数类型“匿名方法”不可分配给参数类型“System.Delegate”

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()?

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

(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.)

(能够做到这一点将完全符合使用匿名方法/lamdas 代替显式委托的概念,这种委托在其他任何地方都如此干净。)

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
    }
}

采纳答案by ilitirit

Try this:

尝试这个:

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

Or:

或者:

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

Or:

或者:

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 */
    }
}

回答by apandit

I've tried a bunch of different methods but none work. ie...

我尝试了很多不同的方法,但都没有奏效。IE...


// Fails -- cannot convert lamda to System.Delegate
mnMnu.BeginInvoke( (DIServer svr)=> {ConfigureMainMenu(server);}, new object[] server);
// Fails -- cannot convert anonymous method to System.Delegate
mnMnu.BeginInvoke( new delegate(DIServer svr){ConfigureMainMenu(server);}, new object[] server);

So, the short answer is no. You could create short helper delegates in the given context and use lambdas to make it a bit neater but that's pretty much it.

所以,简短的回答是否定的。您可以在给定的上下文中创建简短的辅助委托,并使用 lambda 使其更简洁,但仅此而已。

EDIT: Turns out I'm wrong. The methodinvoker answer below works. See this page

编辑:原来我错了。下面的方法调用者答案有效。看这个页面

回答by Jake

You should be able to write something like this:

你应该能够写出这样的东西:

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

回答by Jason

You could write an extension method that would wrap anonymous methods, and even take care of the InvokeRequiredsemantics:

您可以编写一个扩展方法来包装匿名方法,甚至可以处理InvokeRequired语义:

public static void InvokeAction(this Control ctl, Action a)
{
    if (!ctl.InvokeRequired)
    {
        a();
    }
    else
    {
        ctl.BeginInvoke(new MethodInvoker(a));
    }
}

This would allow you to do:

这将允许您执行以下操作:

control.InvokeAction(delegate() { ConfigureMainMenu(server); });

回答by Jason

For completely anonymous methods with a limited number of parameters:

对于参数数量有限的完全匿名方法:

Func<int, int?> caller = new Func<int, int?>((int param1) =>
   {
      return null;
   });

caller.BeginInvoke(7, new AsyncCallback((IAsyncResult ar) =>
{
   AsyncResult result = (AsyncResult)ar;
   Func<int, int?> action = (Func<int, int?>)result.AsyncDelegate;
   action.EndInvoke(ar);
}), null);

You can use one of the other Func delegate types as needed.

您可以根据需要使用其他 Func 委托类型之一。

回答by RckLN

You can do this in a single method by calling invoking yourself:

您可以通过调用自己的方法在单个方法中执行此操作:

  ClassData updData =  new ClassData();

  this.BeginInvoke(new Action<ClassData>(FillCurve),
                           new object[] { updData });

...

...

public void FillCurve(ClassData updData)
{
 ...
}