Threading - ThreadStart versus ParameterizedThreadStart
When we want to create a thread in a .net application we would normally do so by folling these steps.
First include a using statement for the Threading namespace as follows:
We then create a new instance of a thread using the following syntax:
Where in this case the ThreadStart is a delegate which will hold a reference to the DoSomeWork method. If you are unsure of delegates then have a read of the following article first:
The entire DoSomeWork method will look like this:
Our entire test console app will then look like this. Note also the call to thread.Start() to start the thread.
The output of the above code should then look like this:
So this all works very well but what if we want to pass in some arguments to our DoSomeWork method? Well there are two ways of achieving this. Firstly we could create an instance of an object which has the method we are going to run and populate some instance fields prior to passing in the method name to the ThreadStart constructor. If that doesn't quiet make sense then have a look at the following code.
This should yield the following results:
So this is clever but really quite simple way of achieving parameterised threading even though there are no actual parameters, we achieve the same kind of result.
The other way to achieve parameterised queries is to using a different delegate to the ThreadStart delegate. There is another delegate we can use which is called ParameterizedThreadStart. This delegate signature takes an object as a parameter and when we call the Start method on the thread, that is when we pass in our object argument.
Sample code for this might look like this:
Results for this code should be as follows:
So again this is quite a nice way of achieving the desired result.
It is flexible since we can pass in any object but may have to do some casting but otherwise it works well.
Any questions or comments welcome via the form below.