Multithreading in VB.NET


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
		("inside method1 of AClass object i={0}",i)
	end sub

	public sub Method2()
	    Dim i as integer
	    For i = 1 to 100
		("inside method2 of AClass object i={0}",i)
	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))

		th2=new Thread
		(new ThreadStart(addressof obj.method2))

		dim i as integer
		For i= 1 to 100
		    ("Inside the Sub Main i={0} ",i)
	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
  1. Stop() : which stops execution of the thread
  2. Suspend() : which suspends execution of thread
  3. Resume() : which resumes suspended thread
  4. Sleep() : which halts the execution for certain milliseconds

Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a yoga mentor, meditation teacher, and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his private online courses on ASP.NET and meditation go here and here.

Posted On : 04 March 2001

Tags : .NET Framework VB.NET Multithreading Programming Languages