This time we will move delegate method DoAction
to a separate class for better understanding. We will modify the code inside DoAction to use lock features. Let’s add a class CThread in
the application and add the DoAction method in it. In this example to use
SyncLock in it what we are going to do is just to put all lines of code in
DoAction method to be placed between SyncLock Me and End SyncLock constructs.
The complement class code is given below.
Listing 7 – Implementing SyncLock (locking feature)
in thread delegate method
Public Class CThread
Public Sub DoAction()
SyncLock Me
Console.WriteLine("{0} : {1} : To sleep now...", _
Threading.Thread.CurrentThread.ManagedThreadId, Now.ToString())
Threading.Thread.Sleep(5000)
Console.WriteLine("{0} : {1} : is woke up...", _
Threading.Thread.CurrentThread.ManagedThreadId, Now.ToString())
End SyncLock
End Sub
End Class
So we also need minor modification in the Main(). We just need to create object of class CThread in Main() and set thread start delegate method DoAction with class object. The code of Main()
is given below.
Listing 8 – Code for Main method of the application
Sub Main()
Dim oCThread As New CThread()
Console.WriteLine("{0} : {1} : Main thread started...", _
Threading.Thread.CurrentThread.ManagedThreadId, Now.ToString())
Dim oThOneMethod As Threading.ThreadStart = _
New Threading.ThreadStart(AddressOf oCThread.DoAction)
Dim oThTwoMethod As Threading.ThreadStart = _
New Threading.ThreadStart(AddressOf oCThread.DoAction)
Dim oTh1 As Threading.Thread = New Threading.Thread(oThOneMethod)
Dim oTh2 As Threading.Thread = New Threading.Thread(oThTwoMethod)
oTh1.Start()
oTh2.Start()
oTh1.Join()
oTh2.Join()
Console.WriteLine("{0} : {1} : Main thread finishing...", _
Threading.Thread.CurrentThread.ManagedThreadId, Now.ToString())
End Sub
Run the application (CTRL+F5). You should see output window
like:
Figure 3 – Console output of the application with
SyncLock uses
If you look the output carefully you can see that even if
thread 3 has gone to sleep for 5 seconds, thread 4 could not enter the SyncLock
section. In fact thread 4 just waits at the beginning of SyncLock till previous
thread (# 3 here) leaves the SyncLock section. When thread 3 woke up and comes
out of SyncLock section, thread 4 resumes its execution. In the same way, if
there would have been more thread like # 5,6,7 etc, all would have gone into a
thread queue and processed one by one with the rule that only
one thread can enter into the SyncLock at a time.