CHAPTER 19 MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING
Source Code The SimpleMultiThreadApp project is included under the Chapter 19 subdirectory.
Working with the ParameterizedThreadStart Delegate
Recall that the ThreadStart delegate can point only to methods that return void and take no arguments.
While this might fit the bill in some cases, if you want to pass data to the method executing on the
secondary thread, you will need to make use of the ParameterizedThreadStart delegate type. To
illustrate, let’s re-create the logic of the AsyncCallbackDelegate project created earlier in this chapter,
this time making use of the ParameterizedThreadStart delegate type.
To begin, create a new Console Application named AddWithThreads and import the
System.Threading namespace. Now, given that ParameterizedThreadStart can point to any method
taking a System.Object parameter, you will create a custom type containing the numbers to be added,
like so:
class AddParams
{
public int a, b;
public AddParams(int numb1, int numb2)
{
a = numb1;
b = numb2;
}
}
Next, create a static method in the Program class that will take an AddParams parameter and print out
the sum of the two numbers involved, as follows:
static void Add(object data)
{
if (data is AddParams)
{
Console.WriteLine("ID of thread in Add(): {0}",
Thread.CurrentThread.ManagedThreadId);
}
}
AddParams ap = (AddParams)data;
Console.WriteLine("{0} + {1} is {2}",
ap.a, ap.b, ap.a + ap.b);
The code within Main() is straightforward. Simply use ParameterizedThreadStart rather than
ThreadStart, like so:
static void Main(string[] args)
{
Console.WriteLine("***** Adding with Thread objects *****");
Console.WriteLine("ID of thread in Main(): {0}",
Thread.CurrentThread.ManagedThreadId);
717