在C#中调用BeginInvoke/Invoke时如何获取返回值

Mad*_*Boy 39 .net c# multithreading invoke begininvoke

我有这个小方法应该是线程安全的.一切正常,直到我希望它具有回报价值而不是虚空.如何在调用BeginInvoke时获得返回值?

public static string readControlText(Control varControl) {
        if (varControl.InvokeRequired) {
            varControl.BeginInvoke(new MethodInvoker(() => readControlText(varControl)));
        } else {
            string varText = varControl.Text;
             return varText;
        }

    }
Run Code Online (Sandbox Code Playgroud)

编辑:我想在这种情况下让BeginInvoke不是nessecary,因为我需要来自GUI的值才能继续线程.所以使用Invoke也很好.只是不知道如何在以下示例中使用它来返回值.

private delegate string ControlTextRead(Control varControl);
    public static string readControlText(Control varControl) {
        if (varControl.InvokeRequired) {
            varControl.Invoke(new ControlTextRead(readControlText), new object[] {varControl});
        } else {
            string varText = varControl.Text;
             return varText;
        }

    }
Run Code Online (Sandbox Code Playgroud)

但不知道如何使用该代码获得价值;)

Han*_*ant 60

您必须调用Invoke(),以便等待函数返回并获取其返回值.您还需要另一个委托类型.这应该工作:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)


Jus*_*ier 17

EndInvoke可用于从BeginInvoke通话中获取返回值.例如:

    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);
    }
}
Run Code Online (Sandbox Code Playgroud)