Home > Back-end >  How to invoke non-void function on window thread
How to invoke non-void function on window thread

Time:07-18

I was using

  Invoke((MethodInvoker)(() => SendCommand(_monitorCmd, _monitorOutput)));

to launch string SendCommand(string cmd, CommandOutput outputTo) on main window thread but now I also need to read its return value. So I tried:

string rx = Invoke(new Func<string, CommandOutput, string>(
                    (c, m)=> SendCommand(cmd, _monitorOutput)
                    ));

It compiles but throws TargetParameterCountException.

I fixed it using a delegate:

Func<string, CommandOutput, string> del;
string rx = del.Invoke(cmd, _monitorOutput);

But, please, show me where is my error with the lambda code.

CodePudding user response:

You can set a captured variable from inside the lambda

string rx = null;
Invoke(new Action(() => rx = SendCommand(cmd, _monitorOutput)));

Alternatively, you can use the Delegate overload, although this is likely to be much slower

string rx = (string) Invoke(
    new Func<string, CommandOutput, string>(SendCommand),
    _monitorCmd, _monitorOutput);

In this case the arguments must match the parameters exactly.

  • Related