*/
If you have a PH account, you can customize your PH profile.

Other Views

corner
*/

VB.NET School - Lesson 14 - Multithreading in VB.NET - Page 2

Previous Page Next Page



Thread Functionality
The Thread class provides a number of useful methods and properties to control and manage thread execution.

Shared members of the System.Threading.Thread class
The shared property CurrentThread gives a reference to the currently executing thread. Another important shared member of the Thread class is the Sleep() method. It causes the currently executing thread to pause temporarily for the specified amount of time. The Thread.Sleep() method takes as an argument for the amount of time (in milliseconds) for which we want to pause the thread. For example, we can pause the currently executing thread for 1 second by passing 1000 as an argument to the Thread.Sleep() method.

Public Sub Main()
    Console.WriteLine("Before Calling the Thread.Sleep() method")
    Thread.Sleep(1000)   ' blocks the currently executing
                          ' thread (Main thread) for 1 second
    Console.WriteLine("After Calling the Thread.Sleep() method")
End Sub


When you execute the above program, you will notice a delay of 1 second between the printing of the two lines.

Instance members of the System.Threaing.Thread class
The most commonly used instance members of the thread class are:

MemberDescription
NameA property of string type used to get/set the friendly name of the thread instance.
PriorityA property of type System.Threading.ThreadPriority. This property is use to get/set the value indicating the scheduling priority of the thread. The priority can be any instance of the ThreadPriority enumeration which includes AboveNormal, BelowNormal, Normal, Highest and Lowest.
IsAliveA Boolean property indicating whether the thread is alive or has been terminated.
ThreadStateA property of type System.Threading.ThreadState. This property is used to get the value containing the state of the thread. The value returned by this property is an instance of the ThreadState enumeration which includes Aborted, AbortRequested, Suspended, Stopped, Unstarted, Running, WaitSleepJoin, etc
Start()Starts the execution of the thread
Abort()Allows the current thread to stop the execution of a thread permanently. The method throws the ThreadAbortException in the executing thread.
Suspend()Pauses the execution of a thread temporarily
Resume()Resumes the execution of a suspended thread
Join()Makes the current thread wait for another thread to finish
[/size] [/font]

Thread Demonstration Example - Basic Operations
Now we will start to understand the implementation of threads in VB.NET. Review the following VB.NET Console program:

Imports SystemImports System.ThreadingModule Test
    Dim mainThread As Thread
    Dim firstThread As Thread
    Dim secondThread As Thread
    Public Sub Main()
        mainThread = Thread.CurrentThread
        firstThread = New Thread(New ThreadStart(AddressOf Fun1))
        secondThread = New Thread(New ThreadStart(AddressOf Fun2))
        mainThread.Name = "Main Thread"
        firstThread.Name = "First Thread"
        secondThread.Name = "Second Thread"
        ThreadsInfo("Main() before starting the threads")
        firstThread.Start()        secondThread.Start()
        ThreadsInfo("Main() just before exiting the Main()")
    End Sub
    Public Sub ThreadsInfo(ByVal location As String)
        Console.WriteLine(vbCrLf + "In {0}", location)
        Console.WriteLine("Thread Name: {0}, ThreadState: {1}", _
                          mainThread.Name, mainThread.ThreadState)
        Console.WriteLine("Thread Name: {0}, ThreadState: {1}", _
                          firstThread.Name, firstThread.ThreadState)
        Console.WriteLine("Thread Name: {0}, ThreadState: {1}" + vbCrLf, _
                          secondThread.Name, secondThread.ThreadState)
    End Sub
    Public Sub Fun1()
        Dim i As Integer
        For i = 1 To 5
            Console.WriteLine("Fun1() writes: {0}", i)
            Thread.Sleep(100)
        Next
        ThreadsInfo("Fun1()")
    End Sub
    Public Sub Fun2()
        Dim i As Integer
        For i = 10 To 6 Step -1
            Console.WriteLine("Fun2() writes: {0}", i)
            Thread.Sleep(125)
        Next
        ThreadsInfo("Fun2()")
    End Sub
End Module
First of all we have defined three references of type System.Threading.Thread to reference the three threads (main, first and second thread) later in the Main() method:

Dim mainThread As Thread
Dim firstThread As Thread
Dim secondThread As Thread
We have defined a method called ThreadsInfo() to display the information (name and state) of the three threads. The two methods Fun1() and Fun2() are similar to the previous program and just print 5 numbers. In the loop of these methods we have called the Sleep() method which will make the thread executing the method suspend for the specified amount of time. We have set slightly different times in each the threads' Sleep() methods. After the loop, we have printed the information about all the threads again.

    Public Sub Fun2()
        Dim i As Integer
        For i = 10 To 6 Step -1
            Console.WriteLine("Fun2() writes: {0}", i)
            Thread.Sleep(125)
        Next
        ThreadsInfo("Fun2()")
    End Sub
Inside the Main() method we first instantiated the two thread instances (firstThread and secondThread) by passing constructors the references of the Fun1() and Fun2() methods respectively using the ThreadStart delegate. We also made the reference mainThread point to the thread executing the Main() method by using the Thread.CurrentThread property in the Main() method.

    Public Sub Main()
        mainThread = Thread.CurrentThread
        firstThread = New Thread(New ThreadStart(AddressOf Fun1))
        secondThread = New Thread(New ThreadStart(AddressOf Fun2))
We then set the Name property of these threads to the threads corresponding names.

        mainThread.Name = "Main Thread"
        firstThread.Name = "First Thread"
        secondThread.Name = "Second Thread"
After setting the names, we printed the current state of the three threads by calling the static ThreadsInfo() method, started the two threads and finally called the ThreadsInfo() method just before the end of the Main() method.

        ThreadsInfo("Main() before starting the threads")
        firstThread.Start()
        secondThread.Start()
        ThreadsInfo("Main() just before exiting the Main()")
One possible output of the program is:

In Main() before starting the threads
Thread Name: Main Thread, ThreadState: Running
Thread Name: First Thread, ThreadState: Unstarted
Thread Name: Second Thread, ThreadState: Unstarted


In Main() just before exiting the Main()
Thread Name: Main Thread, ThreadState: Running
Thread Name: First Thread, ThreadState: Unstarted
Thread Name: Second Thread, ThreadState: Unstarted

Fun1() writes: 1
Fun2() writes: 10
Fun1() writes: 2
Fun2() writes: 9
Fun1() writes: 3
Fun2() writes: 8
Fun1() writes: 4
Fun2() writes: 7
Fun1() writes: 5

In Fun1()
Thread Name: Main Thread, ThreadState: Background, Stopped, WaitSleepJoin
Thread Name: First Thread, ThreadState: Running
Thread Name: Second Thread, ThreadState: WaitSleepJoin

Fun2() writes: 6

In Fun2()
Thread Name: Main Thread, ThreadState: Background, Stopped, WaitSleepJoin
Thread Name: First Thread, ThreadState: Stopped
Thread Name: Second Thread, ThreadState: Running

Press any key to continue


The important thing to note here is the sequence of execution and the thread states at different points during the execution of the program. The two threads (firstThread and secondThread) didn't get started even when the Main() method was exiting. At the end of firstThread, the Main() thread has stopped while the secondThread is in the Sleep state.


Previous Page Next Page

corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.