Multithreading in VB.NET
Introduction
In past developing multithreaded applications in VB was tedious task. Many times spawning new threads actually spawn errors :-) The picture has changed in VB.NET. VB.NET now has simplicity of Java while dealing with threads. We will see a simple example of running your code in a separate thread in following section
Example of Creating Multithreaded Application
Following is a code from threadtest.vb :
imports System
imports System.Threading
public class AClass
public sub Method1()
Dim i as integer
For i = 1 to 100
Console.Writeline
("inside method1 of AClass object i={0}",i)
next
end sub
public sub Method2()
Dim i as integer
For i = 1 to 100
Console.Writeline
("inside method2 of AClass object i={0}",i)
next
end sub
end class
public class ThreadTest
public shared sub Main()
dim obj as new aclass
dim th1,th2 as thread
th1=new Thread
(new ThreadStart(addressof obj.method1))
th1.start
th2=new Thread
(new ThreadStart(addressof obj.method2))
th2.start
dim i as integer
For i= 1 to 100
Console.WriteLine
("Inside the Sub Main i={0} ",i)
Next
end sub
end class
Let is dissect the example above :
- We have created our own class called AClass which has two methods Method1 and Method2
- These methods simple have a for loop which prints some message on the console
- We have another class which actually uses our AClass class
- In the Main() method we have created instances of Thread class
- Thread class is available in System.Threading namespace and contains properties and methods to deal with threads
- In the constructor of Thread class we have used the ThreadStart class which is a delegate that points to the method that should be executed when a thread is started.
- To actually run the Methods Start() method of the thread is called
- Compile the application using VBC command line compiler as follows
vbc threadtest.vb /t:exe
- When you run the exe you will see the output of two methods and main method mixed up indicating that each method is running concurrently on different threads
- In addition to above methods there are many more methods of thread like
- Stop() : which stops execution of the thread
- Suspend() : which suspends execution of thread
- Resume() : which resumes suspended thread
- Sleep() : which halts the execution for certain milliseconds
10/23/2007 9:31:55 PM
Category
.Net Threadings
Back