Using Monitor Class For Thread Synchronization
While developing a multithreaded application it is very important to maintain synchronization between multiple calls to the same method. Consider for example that you have a function that writes to a file. If at the same time multiple threads call this function it is bound to throw an exception as previous method call is yet to finish with the file. To avoid such situations you can use Monitor class.
Following namespaces are involved in our example:
Using Monitor class
Monitor class can synchronize method calls using its Enter and Exit methods. Following code shows how these methods work:
Dim fs As FileStream = New FileStream
Dim t As Thread = Thread.CurrentThread
fs.Write(Encoding.ASCII.GetBytes(t.Name & vbCrLf),
0, t.Name.Length + 2)
Dim i As Integer
For i = 0 To 10000
fs.Write(Encoding.ASCII.GetBytes(i & “,”),
0, i.ToString().Length + 1)
Here, we called Monitor.Enter method at the start of the method followed by our code that writes into a file. Once the writing operation is complete we call Monitor.Exit method. This ensures that till the time one thread is executing the function any other thread can not execute the same function. You can easily check what happens if you do not use Monitor class by simply commenting these two lines.
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 console.
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.
Using Timer Class
If you have programmed in VB6 before then probably you are familiar with Timer control. The Timer control triggers a code after certain interval of time. This control is typically used on windows forms. Similar control does exists for Windows Forms as well. What if you need such timer functionality on a thread of your classes (not on forms)? The System.Threading.Timer class can be used in such cases. This class automatically uses Thread Pool for executing your code.
Following namespaces are involved:
Using System.Threading.Timer Class
In order to use Timer class you need to create an instance of it as shown below:
Public Sub StartTimer()
Dim tcb As New TimerCallback(AddressOf Me.TimerMethod)
Dim objTimer As Timer
objTimer = New Timer(tcb, Nothing,
Public Sub TimerMethod(ByVal state As Object)
MsgBox(“The Timer invoked this method.”)
Here, we created an instance of Timer class and passed a TimerCallBack and interval details to it. The third parameter represents the delay in milliseconds after which the method will be called for the first time. The forth parameter represents the interval in milliseconds that will be elapsed between the consecutive method calls. In our example the timer will start 5 seconds after creation of the instance. Then after 10 seconds it will fire again and again.