Returning a value from thread?

前端 未结 17 2412
不思量自难忘°
不思量自难忘° 2020-11-27 09:45

How do I return a value from a thread?

17条回答
  •  [愿得一人]
    2020-11-27 10:38

    One of the easiest ways to get a return value from a thread is to use closures. Create a variable that will hold the return value from the thread and then capture it in a lambda expression. Assign the "return" value to this variable from the worker thread and then once that thread ends you can use it from the parent thread.

    void Main()
    {
      object value = null; // Used to store the return value
      var thread = new Thread(
        () =>
        {
          value = "Hello World"; // Publish the return value
        });
      thread.Start();
      thread.Join();
      Console.WriteLine(value); // Use the return value here
    }
    

提交回复
热议问题