beginInvoke,GUI和线程

nir*_*mus 6 c# begininvoke

我有两个线程的应用程序.其中一个(T1)是主GUI形式,另一个(T2)是循环中的功能.当T2得到一些信息必须用GUI形式调用函数.我不确定我做得对.

T2调用函数FUNCTION,以GUI形式更新某些内容.

  public void f() {
        // controler.doSomething();
  }


 public void FUNCTION() {

    MethodInvoker method = delegate {
            f();
    };

    if ( InvokeRequired ) {
        BeginInvoke( method );
    } else {
            f();
    }
 }
Run Code Online (Sandbox Code Playgroud)

但现在我必须宣布两个功能.它如何只使用一个功能?或者它是如何正确的.

Ree*_*sey 16

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

public void Function()
{
     if (this.InvokeRequired)
     {
         this.BeginInvoke(new Action(this.Function));
         return;
     }

     // controller.DoSomething();         
}
Run Code Online (Sandbox Code Playgroud)

编辑以回应评论:

如果需要传递其他参数,可以使用lambda表达式执行,如下所示:

public void Function2(int someValue)
{
     if (this.InvokeRequired)
     {
         this.BeginInvoke(new Action(() => this.Function2(someValue)));
         return;
     }

     // controller.DoSomething(someValue);         
}
Run Code Online (Sandbox Code Playgroud)