Thomas
Thomas

Reputation: 34188

How to run method in separate thread

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

Upvotes: 19

Views: 50447

Answers (5)

Dunc
Dunc

Reputation: 18922

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); });

Upvotes: 15

jgauffin
jgauffin

Reputation: 101150

private static void Method1(int x, int y, int c)
{
    //Method1 implementation
}

static void Main(string[] args)
{
    ThreadPool.QueueUserWorkItem(state => Method1(1,2,3));
}

Upvotes: 3

AMissico
AMissico

Reputation: 21684

Is a "Data Slot" helpful? See "Thread Local Storage: Thread-Relative Static Fields and Data Slots" at http://msdn.microsoft.com/en-us/library/6sby1byh.aspx

Upvotes: 1

JohnC
JohnC

Reputation: 842

If Method1 and Method2 are fairly short-running the best way to do this is not to create a new thread. You can use the .NET thread pool instead, like this:

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

private static void Method2(int x, int y)
{
    //Method2 implementation
}

public static void Main()
{
  ThreadPool.QueueUserWorkItem(() => Method1(4));
  ThreadPool.QueueUserWorkItem(() => Metho2(13, 7));
}

Upvotes: 6

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

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
}

Upvotes: 38

Related Questions