Returning a value from thread?

Asad picture Asad · Aug 21, 2009 · Viewed 187.3k times · Source

How do I return a value from a thread?

Answer

Brian Gideon picture Brian Gideon · Jul 5, 2011

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
}