简体   繁体   中英

Can you use pre-defined Action<T> in Control.BeginInvoke

I have some threading checks and I can get the below working by calling BeginInvoke(new Action<string,string>........ but I was wondering if you can use pre-defined Actions somehow?

private Action<string, string> DoSomething();

private void MakeItHappen(string InputA, string InputB)
{
  if (this.InvokeRequired)
  {
    this.BeginInvoke(DoSomething(InputA, InputB));
  }
  else
  {
     Label.Text = "Done";
     MyOtherGUIItem.Visible = false;
  }

}

Is it this what you mean?

private Action<string, string> _DoSomething;

public void ConfigureToSecondThanFirstByExistingFunction()
{
    _DoSomething = MyMakeItLowerImplementation;
}

public void ConfigureToFirstThenSecondByLambda()
{
    _DoSomething = (a, b) => Console.WriteLine(a + b);
}

public void CallMe()
{
    ConfigureToSecondThanFirstByExistingFunction();
    //ConfigureToFirstThenSecondByLambda();

    _DoSomething("first", "second");
}

private void MyMakeItLowerImplementation(string a, string b)
{
    Console.WriteLine(b + a);
}

If I understood correctly you want something like this?

private delegate void updateDelegate(string p1, string p2);
private updateDelegate DoSomething;

private void MakeItHappen(string InputA, string InputB)
{
    if (this.InvokeRequired)
    {
        this.BeginInvoke(DoSomething, InputA, InputB);
    }
    else
    {
        //Do stuff
    }
}

You have to pass a plain delegate to BeginInvoke . You can use variable capture to wrap up your parameters like this:

private void MakeItHappen(string InputA, string InputB)
{
    if (this.InvokeRequired)
    {
        this.BeginInvoke((Action)delegate () { 
            MakeItHappen(InputA, InputB); 
        });
    }
    else
    {
        // do stuff with InputA and InputB
    }
}

This way?:

private delegate void DoSomethingHandler(string A, string B);
private event DoSomethingHandler DoSomething;

public void Start()
{
   DoSomething = (a, b) => { /*doStuff*/ };
}

private void MakeItHappen(string InputA, string InputB)
{
  if (this.InvokeRequired)
  {
    this.BeginInvoke(DoSomething, InputA, InputB);
  }
  else
  {
    //Do stuff
  }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM