Passing Data to a Thread Entry Method
VB version here.
Originally there was no way to pass data directly to a method that you were using as the entry point for a thread. You had to assign your data to one or more member variables and then retrieve it again in the new thread.
CSharp Code:
private int data;
private void InitiateThread()
{
this.data = 100;
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
}
private void DoWork()
{
int data = this.data;
// Use data here.
}
Many developers would create classes specifically for the new thread that incorporated the data, which was assigned to properties, and the thread entry point.
CSharp Code:
private class Worker
{
private int _data;
public int Data
{
set
{
this._data = value;
}
}
public void DoWork()
{
int data = this._data;
// Use data here.
}
}
private void InitiateThread()
{
Worker w = new Worker();
w.Data = 100;
Thread t = new Thread(new ThreadStart(w.DoWork));
t.Start();
}
With .NET 2.0 came the ParameterizedThreadStart delegate and the ability to pass a single object to the entry method via the Thread.Start method.
CSharp Code:
private void InitiateThread()
{
Thread t = new Thread(new ParameterizedThreadStart(DoWork));
t.Start(100);
}
private void DoWork(object obj)
{
int data = (int)obj;
// Use data here.
}
C# 2.0 also brought with it anonymous methods. This is easier and neater than the old ways and overcomes the weak typing required by the ParameterizedThreadStart delegate. With this new approach you can write a function that takes as many arguments as you like of whatever type you like. You then create a ThreadStart delegate using an anonymous method that calls this function, e.g.
CSharp Code:
private void InitiateThread()
{
Thread t = new Thread(delegate() { DoWork(100); });
t.Start();
}
private void DoWork(int data)
{
// Use data here.
}
Now, C# 3.0 introduces Lambda Expressions, which supercede anonymous methods in most situations.
CSharp Code:
private void InitiateThread()
{
Thread t = new Thread(() => DoWork(100));
t.Start();
}
private void DoWork(int data)
{
// Use data here.
}