Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing parameters to a thread

I want to pass a function that takes a parameter to the ThreadStart Constructor in C#. But, it seems that this is not possible, as I get a syntax error it I try to do something like this

Thread t1 = new Thread(new ThreadStart(func1(obj1));

where obj1 is an object of type List<string> (say).

If I want a thread to execute this function that takes in an object as a parameter, and I plan to create 2 such threads simultaneously with different parameter values what is the best method to achieve this?

like image 612
assassin Avatar asked May 11 '10 16:05

assassin


2 Answers

If you're using .NET 3.5 or higher, one option is to use a lambda for this:

var myThread = new System.Threading.Thread(() => func1(obj1)); 
like image 132
Mark Rushakoff Avatar answered Nov 15 '22 09:11

Mark Rushakoff


You need ParametrizedThreadStart to pass a parameter to a thread.

Thread t1 = new Thread(new ParametrizedThreadStart(func1);
t1.Start(obj1);
like image 28
Thomas Avatar answered Nov 15 '22 08:11

Thomas