Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run method in separate thread

Tags:

.net

c#-4.0

i found a very good piece of code which run all method in separate thread. the code as follows

private static void Method1()
{
    //Method1 implementation
}

private static void Method2()
{
    //Method2 implementation
}

private static void RunMethodInSeparateThread(Action action)
{
    var thread = new Thread(new ThreadStart(action));
    thread.Start();
}

static void Main(string[] args)
{
    RunMethodInSeparateThread(Method1);
    RunMethodInSeparateThread(Method2);
}

in this case how could i pass parameter to method and also there could be situation where Method1 may need 2 parameter and where Method2 may need 3 parameter. in this situation how to construct RunMethodInSeparateThread in generic way which will accept many param and pass to the method. please help me with code. thanks

like image 708
Thomas Avatar asked Mar 25 '11 13:03

Thomas


People also ask

How do you call a method in a separate thread in Java?

Java Thread run() methodThe run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.

Does Async run on another thread C#?

No, it does not. It MAY start another thread internally and return that task, but the general idea is that it does not run on any thread.

What is start method in Java?

start() method causes this thread to begin execution, the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).


2 Answers

To run some code in another thread you could do:

new Thread(delegate () {
    Method1(param1, param2);
}).Start();

You could accept a collection of parameters or a dictionary for your methods that need to accept a variable number of parameters. Or you could create separate methods that allow a different number of parameters. For example:

private static void Method1()
{
    //Method1 implementation
}

private static void Method1(int Param1)
{
    //Method1 implementation
}

private static void Method1(int Param1, int Param2)
{
    //Method1 implementation
}
like image 174
FreeAsInBeer Avatar answered Oct 04 '22 02:10

FreeAsInBeer


With .NET 4, your RunMethodInSeparateThread method seems a bit redundant in my opinion. I would just do this:

Task.Factory.StartNew(() => { Method1(param1); });
Task.Factory.StartNew(() => { Method2(param1, param2); });
like image 37
Dunc Avatar answered Oct 04 '22 04:10

Dunc