Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

beginInvoke, GUI and thread

Tags:

c#

begininvoke

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.

like image 214
nirmus Avatar asked Jun 07 '11 16:06

nirmus


2 Answers

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);         
}
like image 89
Reed Copsey Avatar answered Nov 19 '22 09:11

Reed Copsey


Looks good to me. You may be able to change the anonymous delegate to a lambda, which is a little cleaner. To get rid of the f() method declaration, you can inline its code into the delegate, then either Invoke the delegate as a MethodInvoker or simply call it like you would any other method:

 public void FUNCTION() {

    MethodInvoker method = ()=> controller.doSomething();

    if ( InvokeRequired ) {
        BeginInvoke( method );
    } else {
            method();
    }
 }
like image 24
KeithS Avatar answered Nov 19 '22 11:11

KeithS