How to get return value when BeginInvoke/Invoke is called in C# How to get return value when BeginInvoke/Invoke is called in C# multithreading multithreading

How to get return value when BeginInvoke/Invoke is called in C#


You have to Invoke() so you can wait for the function to return and obtain its return value. You'll also need another delegate type. This ought to work:

public static string readControlText(Control varControl) {  if (varControl.InvokeRequired) {    return (string)varControl.Invoke(      new Func<String>(() => readControlText(varControl))    );  }  else {    string varText = varControl.Text;    return varText;  }}


EndInvoke may be used to get a return value from a BeginInvoke call. For example:

    public static void Main()     {        // The asynchronous method puts the thread id here.        int threadId;        // Create an instance of the test class.        AsyncDemo ad = new AsyncDemo();        // Create the delegate.        AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);        // Initiate the asychronous call.        IAsyncResult result = caller.BeginInvoke(3000,             out threadId, null, null);        Thread.Sleep(0);        Console.WriteLine("Main thread {0} does some work.",            Thread.CurrentThread.ManagedThreadId);        // Call EndInvoke to wait for the asynchronous call to complete,        // and to retrieve the results.        string returnValue = caller.EndInvoke(out threadId, result);        Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",            threadId, returnValue);    }}


public static string readControlText(Control varControl){    if (varControl.InvokeRequired)    {        string res = "";        var action = new Action<Control>(c => res = c.Text);        varControl.Invoke(action, varControl);        return res;    }    string varText = varControl.Text;    return varText;}