Introduction
Programming threads can be a very complex task if you don't have a clear strategy from the first code segment written. Trying to solve thread synchronization issues "live" can take a lot of time, and much could be saved if the developer has a more paranoid attitude when programming threads. I will not try to teach advanced thread programming, but only show a simple usage of sending parameters at thread start. What I find missing in many articles is the intermediary levels in thread programming, between the most simple thread examples and the more complex subjects.
Using the code
Unfortunately, you are only allowed to send in one parameter to the method, and this one parameter has to be of type object
, but apart from that, you can wrap whatever you want in this object, from general classes to your own objects. My code segment will send an ArrayList
as the parameter. To setup a thread startup with a parameter, you need to use the ParameterizedThreadStart
which is a delegate located in the System.Threading
namespace.
The delegate is setup by the following code segment:
ParameterizedThreadStart pts =
new ParameterizedThreadStart(MyParameterizedMethod);
My locale method needs the following signature:
private void MyParameterizedMethod(Object o)
{
...
}
So now I am ready to use my method and the delegate. I then initalize everything as normal, only that I now specify a parameter to the Start
method of the Thread
class (I don't need to explicitly cast the ArrayList
object).
ParameterizedThreadStart pts =
new ParameterizedThreadStart(MyParameterizedMethod);
Thread t = new Thread(pts);
ArrayList al = new ArrayList();
al.Add("Hei");
al.Add(2);
t.Start(al);
The same applies when using the ThreadPool
to run background threads, which also is the recommendation from Microsoft. But here, we use a WaitCallback
instead of the ParameterizedThreadStart
.
WaitCallback myCallback = new WaitCallback(MyParameterizedMethod);
if (!ThreadPool.QueueUserWorkItem(myCallback, al))
{
throw new Exception("Not able to queue work item");
}
Paal started as a software consultant in 2000, where he has been working with everything from embedded C to Java, C++, Uniface and C#.
http://www.iserialized.com