Passing Parameter to Thread
Problem
Threads in .NET must start a functions which is void() (return no values and gets no parameters). But what if we want to pass parameters to the thread?
Solution
The parameter will be stored as a private member of the class:
-------------------------------
public class MyClass{
public void DoSomething()
{
Thread t = new Thread(new ThreadStart(DoSomethingInThread));
_parameterForThread = 5;
t.Start();
}
private int _parameterForThread = -1;
private void DoSomethingInThread()
{
_parameterForThread ++;
}
}
------------------------------------------
Alternative Solution
This is not so elegant, because we need to store local data in a member (which does not necessary represent the class's state).
So to take the concept one step further, we can put all the relevant code in another class:
------------------------------------------
public class MyThread
{
public MyThread(int parameterForThread )
{
_parameterForThread = parameterForThread ;
}
private int _parameterForThread = -1;
public void DoSomethingInThread()
{
_parameterForThread ++;
}
}
public class MyClass
{
public void DoSomething()
{
MyThread mt = new MyThread(5);
Thread t = new Thread(new ThreadStart(mt.DoSomethingInThread));
t.Start();
}
}
------------------------------------------
1 Comments:
Thanks Yariv,
You helped me to much.
Post a Comment
<< Home