Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 875
ratty Avatar asked Apr 15 '10 05:04

ratty


People also ask

How do you return a value from a thread?

There are two main ways to return values from a thread, they are: Extend threading. Thread and store data in instance variables. Store data in global variables.

Can you pass arguments to a thread?

You can only pass a single argument to the function that you are calling in the new thread. Create a struct to hold both of the values and send the address of the struct. Save this answer.

How do you pass multiple arguments to a thread?

Passing Multiple Arguments to Threads. When passing multiple arguments to a child thread, the standard approach is to group the arguments within a struct declaration, as shown in Code Listing 6.9. The address of the struct instance gets passed as the arg to pthread_create() .

Can we return value from thread C#?

Threads do not really have return values. However, if you create a delegate, you can invoke it asynchronously via the BeginInvoke method. This will execute the method on a thread pool thread. You can get any return value from such as call via EndInvoke .


4 Answers

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
});
like image 69
Marc Gravell Avatar answered Nov 12 '22 21:11

Marc Gravell


This may be another approach. Here input is passed as parameterized Thread and return type is passed in the delegate event, so that when the thread complete that will call the Delegate. This will be fine to get result when the thread completes.

 public class ThreadObject
    {
        public int i;
        public int j;
        public int result;
        public string Name;
    }



    public delegate void ResultDelegate(ThreadObject threadObject);

    public partial class Form1 : Form
    {

        public event ResultDelegate resultDelete;

        public Form1()
        {
            InitializeComponent();

            resultDelete += new ResultDelegate(resultValue);
        }

        void resultValue(ThreadObject threadObject)
        {
            MessageBox.Show("Thread Name : " + threadObject.Name + " Thread Value : " + threadObject.result);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ThreadObject firstThreadObject = new ThreadObject();
            firstThreadObject.i = 0;
            firstThreadObject.j = 100;
            firstThreadObject.Name = "First Thread";

            Thread firstThread = new Thread(Fun);
            firstThread.Start(firstThreadObject);


            ThreadObject secondThreadObject = new ThreadObject();
            secondThreadObject.i = 0;
            secondThreadObject.j = 200;
            secondThreadObject.Name = "Second Thread";

            Thread secondThread = new Thread(Fun);
            secondThread.Start(secondThreadObject);

        }


        private void Fun(object parameter)
        {
            ThreadObject threadObject = parameter as ThreadObject;

            for (; threadObject.i < threadObject.j; threadObject.i++)
            {
                threadObject.result += threadObject.i;

                Thread.Sleep(10);
            }

            resultValue(threadObject);
        }
    }
like image 41
Mohanavel Avatar answered Nov 12 '22 22:11

Mohanavel


I like Mark Gravell's answer. You can pass your result back out to the main thread with just a little modification:

int fun1, fun2;
Thread FirstThread = new Thread(() => {
    fun1 = Fun1(5, 12);
});
Thread SecondThread = new Thread(() => {
    fun2 = Fun2(2, 3); 
});

FirstThread.Start();
SecondThread.Start();
FirstThread.Join();
SecondThread.Join();

Console.WriteLine("Fun1 returned {0}, Fun2 returned {1}", fun1, fun2);
like image 36
YakkoWarner Avatar answered Nov 12 '22 21:11

YakkoWarner


There is much simpler way to execute function in separate thread:

// Create function delegate (it can be any delegate)
var FunFunc = new Func<int, int, int>(fun1);
// Start executing function on thread pool with parameters
IAsyncResult FunFuncResult = FunFunc.BeginInvoke(1, 5, null, null);
// Do some stuff
// Wait for asynchronous call completion and get result
int Result = FunFunc.EndInvoke(FunFuncResult);

This function will be executed on thread pool thread, and that logic is completely transparent to your application. An in general, I suggest to execute such small tasks on thread pool instead of dedicated thread.

like image 34
arbiter Avatar answered Nov 12 '22 21:11

arbiter