Reputation: 390
I'm trying to create a new thread passing two parameters, I have searched too many times but still no result. Here is my method:
public void Add(int smallest, int biggest)
{
for (int i = smallest; i < biggest+1; i++)
{
Thread.Sleep(500);
result = result + i;
}
}
And I want to do as below:
static void Main()
{
int x=10;
int y=100;
// in this line appear error
Thread t=new Thread(Add);
t.start(x,y);
}
Upvotes: 0
Views: 1811
Reputation: 17485
public class ThreadObj
{
public int smallest {get;set;}
public int biggest {get;set;}
}
public void Add(object obj)
{
ThreadObj myObj = (ThreadObj)obj;
for (int i = myObj.smallest; i < myObj.biggest+1; i++)
{
Thread.Sleep(500);
result = result + i;
}
}
static void Main()
{
Thread t=new Thread(Add);
t.start(new ThreadObj(){ smallest = 10, biggest = 100});
}
Thread method only accept object as parameter. So you have to create object and pass value as object into that thread.
Upvotes: 0
Reputation: 70652
You can't do it that way. The Thread.Start()
method doesn't include overloads supporting more than one parameter.
However, the general goal is easily solved using an anonymous method as your thread body:
static void Main()
{
int x=10;
int y=100;
// in this line appear error
Thread t=new Thread(() => Add(x, y));
t.start();
}
I.e. instead of your Add()
method being the thread entry point, you wrap it in an anonymous method (declared here via the lambda expression syntax). The arguments x
and y
are "captured" by the anonymous method, to be passed into the Add()
method when the thread starts.
One very important caution: the values from the variables are only retrieved when the Add()
method is actually called. That is when the thread starts. If you modify their values before that happens, the new values are what are used.
This idiom is usable in any context where you want to pass strongly-typed and/or multiple arguments to a method where normally the API would allow none or some fixed number (like just one). Event handlers, Task
entry points, I/O callbacks, etc. all can benefit from this approach.
Upvotes: 3