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
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.
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.
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).
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
}
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With