Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have application with two thread. One of them (T1) is main GUI form, another (T2) is function working in loop. When T2 gets some information must call function with GUI form. I'm not sure that I do it right.

T2 call function FUNCTION, which update something in GUI form.

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


 public void FUNCTION() {

    MethodInvoker method = delegate {
            f();
    };

    if ( InvokeRequired ) {
        BeginInvoke( method );
    } else {
            f();
    }
 }

But now I must declare two function. How does it using only one function? Or how does it right.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
537 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

     // controller.DoSomething();         
}

Edit in response to comments:

If you need to pass additional arguments, you can do it by using a lambda expression as follows:

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

     // controller.DoSomething(someValue);         
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...