Pass Parameters through ParameterizedThreadStart
Solution 1:
lazyberezovsky has the right answer. I want to note that technically you can pass an arbitrary number of arguments using lambda expression due to variable capture:
var thread = new Thread(
() => DoMethod(a, b, c));
thread.Start();
This is a handy way of calling methods that don't fit the ThreadStart
or ParameterizedThreadStart
delegate, but be careful that you can easily cause a data race if you change the arguments in the parent thread after passing them to the child thread's code.
Solution 2:
Use overloaded Thread.Start
method, which accepts object (you can pass your custom type or array if you need several parameters):
Foo parameter = // get parameter value
Thread thread = new Thread(new ParameterizedThreadStart(DoMethod));
thread.Start(parameter);
And in DoMethod
simply cast argument to your parameter type:
private void DoMethod(object obj)
{
Foo parameter = (Foo)obj;
// ...
}
BTW in .NET 4.0 and above you can use tasks (also be careful with race conditions):
Task.Factory.StartNew(() => DoMethod(a, b, c));
Solution 3:
Instead of creating a class to pass in multiple parameters as @user1958681 has done, you could use anonymous types, then just use the dynamic typing to extract your parameters.
class MainClass
{
int A = 1;
string B = "Test";
Thread ActionThread = new Thread(new ParameterizedThreadStart(DoWork));
ActionThread.Start(new { A, B});
}
Then in DoWork
private static void DoWork(object parameters)
{
dynamic d = parameters;
int a = d.A;
string b = d.B;
}
Solution 4:
Another way to archive what you want, is by returning a delegate within your function / method. Take the following example:
class App
{
public static void Main()
{
Thread t = new Thread(DoWork(a, b));
t.Start();
if (t.IsAlive)
{
t.IsBackground = true;
}
}
private static ThreadStart DoWork(int a, int b)
{
return () => { /*DoWork*/ var c = a + b; };
}
}
Solution 5:
new Thread(() => { DoMethod(a, b, c); }).Start();
or
new Thread(() => DoMethod(a, b, c)).Start();