Ed King
Ed King

Reputation: 1863

How do I return values from an asynchronous call in C#?

I have a C# form that I've talking to from another thread, using the Invoke methodology detailed on MSDN. Invoking the method on the main thread works, and here's a snippet of the basic structure:

// In the main thread:
public void doCommand(int arg, out int ret) {
    ret = arg + 1;
}

// On another thread:
public delegate void CmdInvoke(int arg, out int ret);

public void execute() {
    CmdInvoke d = new CmdInvoke(Program.form.doCommand);
    int a = 0;
    int b = 0;
    Program.form.Invoke(d, new object[] { a, b });

    // I want to use b now...
}

As described above, I now want to return the parameter b back to the calling thread. At the moment, b is always 0. I've read that maybe I need to use BeginInvoke and EndInvoke, but I'm a bit confused to be honest How can I get at b? I don't mind if it's an out parameter or a return, I just want it somehow!

Upvotes: 1

Views: 111

Answers (1)

Alex
Alex

Reputation: 942

You can get the updated value from doCommand in such a way (return new value in the ordinary way with return not as an out parameter):

// In the main thread:
public int doCommand(int arg) {
    return arg + 1;
}

// On another thread:
public delegate int CmdInvoke(int arg);

public void execute() {
    CmdInvoke d = new CmdInvoke(Program.form.doCommand);
    int a = 0;
    int b = 0;
    b = (int)Program.form.Invoke(d, new object[] { a });
    // Now b is 1
}

An out parameter doesn't work because when you put b into the array object[] the copy of b is actually contained in the array (because of boxing). And consequently method doCommand changes that copy not the original b variable.

Upvotes: 1

Related Questions