Visual Basic .NET allows application developers to create multithreaded applications. This was not possible in earlier versions of Visual Basic. This is done with the help of classes from the Microsoft .NET Framework class library. Specifically, the namespace System.Threading is used for providing multithreading capability to the applications. The following code examples can be found in the ThreadApplication folder for this chapter. This code illustrates the multithreading capabilities offered to the Visual Basic .NET language by the .NET Framework. Imports System Imports System.Threading Public Class ThreadedClass Public Sub Method1() Dim ILoopCounter As Integer For ILoopCounter = 1 To 10 Console.WriteLine("From method 1") Next End Sub Public Sub Method2() Dim ILoopCounter As Integer For ILoopCounter = 1 To 10 Console.WriteLine("From method 2") Next End Sub End Class The class ThreadedClass defines two simple methods. The following main module shows how the methods of the class are called in a multithreaded environment: Imports System Imports System.Threading Module ThreadModule Sub Main() Console.WriteLine("This is the main thread.") Dim objThreadedClass As New ThreadedClass() Dim t1 As New Thread(New ThreadStart _ (AddressOf objThreadedClass.Method1)) t1.Priority = ThreadPriority.BelowNormal Dim t2 As New Thread(New ThreadStart _ (AddressOf objThreadedClass.Method2)) t2.Priority = ThreadPriority.AboveNormal t1.Start() t2.Start() t1.Join() t2.Join() Console.WriteLine("Threads in method 1 " &_ "and method 2 have terminated.") Console.ReadLine() End Sub End Module In Visual Basic .NET, the main module execution forms a thread of execution by default. In the preceding code, we are forming two additional threads. In the first, the Method1 of the class ThreadedClass is executed, and in the second thread the other method is executed. The priorities of all the threads are normal by default. This can be changed in the code. The thread execution is started with the Start method of the Thread object. Note that the main thread waits for the children threads to finish. This is accomplished with the help of the Join method. As you can see, Visual Basic .NET allows developers to create powerful multithreaded applications with the help of the classes defined in the System.Threading namespace of the Microsoft .NET Framework class library. |