Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass more than one parameter to a C# thread?

How to pass more than one parameter to a C# thread? Any example will be appreciated.

like image 606
Techee Avatar asked Mar 22 '10 05:03

Techee


2 Answers

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()
like image 105
Oscar Mederos Avatar answered Oct 07 '22 14:10

Oscar Mederos


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)
{

}
like image 42
Chris S Avatar answered Oct 07 '22 13:10

Chris S