Returning a value from thread?

Viewed 222693

How do I return a value from a thread?

19 Answers

I came across this thread when also trying to obtain the return value of a method that gets executed within a Thread. I thought I would post my solution that works.

This solution uses an class to store both the method to be executed (indirectly) and stores the returning value. The class can be used for any function and any return type. You just instantiate the object using the return value type and then pass the function to call via a lambda (or delegate).


C# 3.0 Implementation


public class ThreadedMethod<T>
{

    private T mResult;
    public T Result 
    {
        get { return mResult; }
        private set { mResult = value; }
    }

    public ThreadedMethod()
    {
    }

    //If supporting .net 3.5
    public void ExecuteMethod(Func<T> func)
    {
        Result = func.Invoke();
    }

    //If supporting only 2.0 use this and 
    //comment out the other overload
    public void ExecuteMethod(Delegate d)
    {
        Result = (T)d.DynamicInvoke();
    }
}

To use this code you can use a Lambda (or a delegate). Here is the example using lambdas:

ThreadedMethod<bool> threadedMethod = new ThreadedMethod<bool>();
Thread workerThread = new Thread((unused) => 
                            threadedMethod.ExecuteMethod(() => 
                                SomeMethod()));
workerThread.Start();
workerThread.Join();
if (threadedMethod.Result == false) 
{
    //do something about it...
}

VB.NET 2008 Implementation


Anyone using VB.NET 2008 can't use lambdas with non-value returning methods. This affects the ThreadedMethod class, so we'll make ExecuteMethod return the value of the function. This doesn't hurt anything.

Public Class ThreadedMethod(Of T)

    Private mResult As T
    Public Property Result() As T
        Get
            Return mResult
        End Get
        Private Set(ByVal value As T)
            mResult = value
        End Set
    End Property

    Sub New()
    End Sub

    'If supporting .net 3.5'
    Function ExecuteMethod(ByVal func As Func(Of T)) As T
        Result = func.Invoke()
        Return Result
    End Function

    'If supporting only 2.0 use this and' 
    'comment out the other overload'
    Function ExecuteMethod(ByVal d As [Delegate]) As T
        Result = DirectCast(d.DynamicInvoke(), T)
        Return Result
    End Function

End Class

Can use This Code:

 private Object MyThread(Object Data)
      {
        Object response = null;
        Thread newThread = new Thread(() =>
        {
            response = MyFunction(Data);
            //MyFunction Is Function that you Define
        });
        newThread.Start();
        newThread.Join();
        return response;
      }
class Program
{
    public static void ActionResultPrint(string i)
    {
        Console.WriteLine(i);
    }

    static void Main(string[] args)
    {
        var tl = new List<Thread>();

        tl.Add(new Thread(() => Run(10, ActionResultPrint)));
        tl.Add(new Thread(() => Run(20, ActionResultPrint)));
        tl.ForEach(x => x.Start());
        tl.ForEach(x => x.Join());
    }

    public static void Run(int j, Action<string> action)
    {
        string rvalue = string.Empty;

        for (int i = 0; i <= j; i++)
        {
            Thread.Sleep(100);
            rvalue = i.ToString();
            Console.WriteLine(rvalue);
        }
        action($@"output {j}");
    }
}

when threads are used , value can be passed and returned in following ways:

int value = -1;
  Thread t1 = new Thread(() => { value = compute(a); });
   t1.Start();
 if(value!=-1)
 {...}

   public int compute(int[] a1)
    {
    //...code logic
        return -1;
    }
Related