Part 89 - ParameterizedThreadStart delegate

In this video we will discuss the purpose of ParameterizedThreadStart delegate. This is continuation to Part 88. Please watch Part 88 before proceeding. We will be working with the same example we worked with in Part 88.

Use ParameterizedThreadStart delegate to pass data to the thread function. Here is an example that shows the usage of ParameterizedThreadStart delegate.

usingSystem;

usingSystem.Threading;

namespaceThreadStartDelegateExample

{

classProgram

{

publicstaticvoidMain()

{

Console.WriteLine("Please enter the target number");

objecttarget=Console.ReadLine();

// Create an instance
ParameterizedThreadStart delegate

ParameterizedThreadStartparameterizedThreadStart=

newParameterizedThreadStart(Number.PrintNumbers);

ThreadT1=newThread(parameterizedThreadStart);

// Pass the traget number to the start
function, which

// will then be passed automatically
to PrintNumbers() function

T1.Start(target);

}

}

classNumber

{

publicstaticvoidPrintNumbers(objecttarget)

{

intnumber=0;

if (int.TryParse(target.ToString(), outnumber))

{

for (inti=1; i<=number; i++)

{

Console.WriteLine(i);

}

}

}

}

}

The code in the Main() function can also be written as shown below.

publicstaticvoidMain()

{

Console.WriteLine("Please
enter the target number");

objecttarget=Console.ReadLine();

ThreadT1=newThread(Number.PrintNumbers);

T1.Start(target);

}

Here we are not explicitly creating an instance of ParameterizedThreadStart delegate. Then how is it working?It's working because, the compiler implicitly converts newThread(Number.PrintNumbers) to newThread(newParameterizedThreadStart(Number.PrintNumbers)).

When to use ParameterizedThreadStart over ThreadStart delegate?Use ParameterizedThreadStart delegate if you have some data to pass to the Thread function, otherwise just use ThreadStart delegate.

Please note: Using ParameterizedThreadStart delegate and Thread.Start(Object) method to pass data to the Thread function is not type safe as they operate on object datatype and any type of data can be passed. If you try to change the data type of the target parameter of PrintNumbers() function from object to int, a compiler error will be raised as the signature of PrintNumbers() function does not match with the signature of ParameterizedThreadStart delegate.

Next Video: Passing data to the Thread function without loosing the type safety.

1 comment:

I have been watching many of your videos on you tube and they are so helpful. Also reading from your blog. Thank you so much for all these excellent tutorials. You are helping so much ! all is so clear and so well explained.