How to pass more than one parameter to a C# thread? Any example will be appreciated.
Suppose you have a method:
void A(string a, int b) {}
This should work (.NET 2.0):
ThreadStart starter = delegate { A("word", 10); };
Thread thread = new Thread(starter);
thread.Start();
And the following (shorter) for higher versions:
ThreadStart starter = () => A("word", 10);
Thread thread = new Thread(starter);
//or just...
//Thread thread = new Thread(() => A("word",10));
thread.start()
For C# 3.0 you can avoid the ugly object array passing with anonymous methods:
void Run()
{
string param1 = "hello";
int param2 = 42;
Thread thread = new Thread(delegate()
{
MyMethod(param1,param2);
});
thread.Start();
}
void MyMethod(string p,int i)
{
}
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