Create a console application and update the code in module
as given below.
Listing 5 – Implementing thread creation without
using Sleep and Join methods
Module Module1
Sub Main()
Console.WriteLine("{0} : {1} : Main thread started...", _
Threading.Thread.CurrentThread.ManagedThreadId, Now.ToString())
Dim oThOneMethod As Threading.ThreadStart = _
New Threading.ThreadStart(AddressOf DoAction)
Dim oThTwoMethod As Threading.ThreadStart = _
New Threading.ThreadStart(AddressOf DoAction)
Dim oTh1 As Threading.Thread = New Threading.Thread(oThOneMethod)
Dim oTh2 As Threading.Thread = New Threading.Thread(oThTwoMethod)
oTh1.Start()
oTh2.Start()
Console.WriteLine("{0} : {1} : Main thread finishing...", _
Threading.Thread.CurrentThread.ManagedThreadId, Now.ToString())
End Sub
Public Sub DoAction()
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 Sub
End Module
** [Please note that you should use
CTRL+F5 key combination to run the application with code provided in this
article since I have not used Console.Read() at the end of Main(). CTRL+F5
will cause the console to wait for any key press at the end. This way you can
see the output in the console window. Otherwise you can add Console.Read() in
main().]
|
If you run this application (CTRL+F5), you will get output
in console window a given below.
Figure 1 – Console output of application
Does the result seem proper? No, because in general we don’t
want to stop the main thread before finishing generated threads. Here is what
we need to use Join() method which will wait till new
threads finish. Modify the Main()
method to use Join() as given below. I have only
added oTh1.Join() and oTh2.Join()
in the Main() method.
Listing 6 – Implementing thread creation using
Sleep and Join methods
Sub Main()
Console.WriteLine("{0} : {1} : Main thread started...", _
Threading.Thread.CurrentThread.ManagedThreadId, Now.ToString())
Dim oThOneMethod As Threading.ThreadStart = _
New Threading.ThreadStart(AddressOf DoAction)
Dim oThTwoMethod As Threading.ThreadStart = _
New Threading.ThreadStart(AddressOf 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
Now run the application (CTRL+F5), you should see following
console output.
Figure 2 – Console output of the application
This time result is as we wanted. New threads are finished
before the main thread.