Problem
How do you start a thread with parameters in C#?
Asked by JL.
Solution #1
One of the 2 overloads of the Thread constructor takse a ParameterizedThreadStart delegate which allows you to pass a single parameter to the start method. Unfortunately though it only allows for a single parameter and it does so in an unsafe way because it passes it as object. I find it’s much easier to use a lambda expression to capture the relevant parameters and pass them in a strongly typed fashion.
Try the following
public Thread StartTheThread(SomeType param1, SomeOtherType param2) {
var t = new Thread(() => RealStart(param1, param2));
t.Start();
return t;
}
private static void RealStart(SomeType param1, SomeOtherType param2) {
...
}
Answered by JaredPar
Solution #2
Yep :
Thread t = new Thread (new ParameterizedThreadStart(myMethod));
t.Start (myParameterObject);
Answered by Erick
Solution #3
Lambda expressions can be used.
private void MyMethod(string param1,int param2)
{
//do stuff
}
Thread myNewThread = new Thread(() => MyMethod("param1",5));
myNewThread.Start();
This is the finest answer I’ve seen so far; it’s quick and simple.
Answered by Georgi-it
Solution #4
Thread thread = new Thread(Work);
thread.Start(Parameter);
private void Work(object param)
{
string Parameter = (string)param;
}
An object must be the parameter type.
EDIT:
While this answer isn’t inaccurate, I would advise against it. It’s considerably easier to interpret a lambda expression because it doesn’t require type casting. See https://stackoverflow.com/a/1195915/52551 for more information.
Answered by Spencer Ruport
Solution #5
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod));
t.Start("My Parameter");
}
static void ThreadMethod(object parameter)
{
// parameter equals to "My Parameter"
}
}
Answered by huseyint
Post is based on https://stackoverflow.com/questions/1195896/threadstart-with-parameters