Using ThreadPool Class
You can use Thread class directly to create and run a new thread. Even though creating threads in this fashion is easy there is still easier way to do that. ThreadPool class allows you to simply place a function in a queue which is executed by the ThreadPool. ThreadPool internally maintains a pool of threads that are used to execute your code as and when required. In fact ThreadPool operations are more efficient that using Thread class directly.
Following namespaces are involved:
The QueueUserWorkItem method of ThreadPool class simply accepts an instance of type WaitCallback. The WaitCallback class in turn accepts an address of the function you want to execute. The QueueUserWorkItem method basically puts your function in queue and executes as and when a thread is available. Following example shows how this method is used:
Public Sub QueueUserWorkItemTest()
Dim wc As New WaitCallback(AddressOf MyWaitCallback)
Public Sub MyWaitCallback(ByVal state As Object)
- We first created an instance of WaitCallBack delegate passing it the
address of our function.
- We then call shared method - QueueUserWorkItem - of ThreadPool class that
accepts this delegate as a parameter.
- The function that will be run over the thread simply outputs some text on
The RegisterWaitForSingleObject method of ThreadPool class accepts an instance WaitHandle class and WaitOrTimerCallback class. WaitHandle class is typically an instance of AutoResetEvent or ManualResetEvent. These classes basically signal to the ThreadPool that your function can now be called. WaitOrTimerCallback instance is nothing but a delegate for your function. Following code shows how this method is used:
Public Sub ShowDemoRegisterWaitForSingleObject()
Dim wtc As New
Dim myevent As New AutoResetEvent(False)
(myevent, wtc, Nothing, 20000, True)
Public Sub MyWaitOrTimerCallback
(ByVal state As Object, ByVal timeout As Boolean)
- We first create a WaitOtTimerCallBack delegate by passing it the address
of our function.
- Next, we create an instance of AutoResetEvent.
- RegisterWaitForSingleObject method of ThreadPool class is then called.
- Note that unless you call Set() method on the AutoResetEvent, your
function will not be executed. Calling this method indicates to ThreadPool
that the method can now be called on a thread from the pool.
I hope you must have found the article useful. In the next article, I
will show you how to use System.Threading.Timer class to execute your
function repeatedly after certain time interval.