How to call the method in thread with arguments and return some value

ratty picture ratty · Apr 15, 2010 · Viewed 56.4k times · Source

I like to call the method in thread with arguments and return some value here example

class Program
{
    static void Main()
    {
        Thread FirstThread = new Thread(new ThreadStart(Fun1));
        Thread SecondThread = new Thread(new ThreadStart(Fun2));
        FirstThread.Start();
        SecondThread.Start();
    }
    public static void Fun1()
    {
        for (int i = 1; i <= 1000; i++)
        {
            Console.WriteLine("Fun1 writes:{0}", i);
        }
    }
    public static void Fun2()
    {
        for (int i = 1000; i >= 6; i--)
        {
            Console.WriteLine("Fun2 writes:{0}", i);
        }
    }
}

I know this above example run successfully but if method fun1 like this

public int fun1(int i,int j)
{
    int k;
    k=i+j;
    return k;
}

then how can I call this in thread?

Answer

Marc Gravell picture Marc Gravell · Apr 15, 2010

You should be able to use an anonymous method or lambda to provide full static checking:

Thread FirstThread = new Thread(() => Fun1(5, 12));

or if you want to do something with the result:

Thread FirstThread = new Thread(() => {
    int i = Fun1(5, 12);
    // do something with i
});

but note that this "do something" still runs in the context of the new thread (but with access to the other variables in the outer method (Main) courtesy of "captured variables").

If you have C# 2.0 (and not above), then:

Thread FirstThread = new Thread((ThreadStart)delegate { Fun1(5, 12); });

and

Thread FirstThread = new Thread((ThreadStart)delegate {
    int i = Fun1(5, 12);
    // do something with i
});