Free since 2005 · No login required
AT

Academic Tutorials

Learn at your own pace

site-mobile-top-banner · 320x50

Multithreading in VB.Net

Added 29 Jul 2008

The .NET Framework, and thus VB.NET provides full support for multiple execution threads in a program. You can add threading functionality to your application by using the System.Threading namespace. A thread in .NET is represented by the System.Threading.Thread class. We can create multiple threads in our program by creating multiple instances (objects) of this class. A thread starts its execution by calling the specified method and terminates when the execution of that method gets completed. We can specify the method name that the thread will call when it starts by passing a delegate of the ThreadStart type in the Thread class constructor. The delegate System.Threading.ThreadStart may reference any method which has the void return type and which takes no arguments.

Public Delegate Sub ThreadStart()

For example, we can change our previous application to run the two methods in two different threads like this:

Dim firstThread As New Thread(New ThreadStart(AddressOf Fun1))

Dim secondThread As New Thread(New ThreadStart(AddressOf Fun2))
Here we have created two instances of the Thread class and passed a
ThreadStart type delegate in the constructor which references a method
in our program. It is important that the method referenced in the
Thread class constructor, through the ThreadStart delegate is
parameter-less and has no return type. A thread does not start its
execution when its object is created. Rather, we have to start the
execution of a thread by calling the Start() method of the Thread
class.


firstThread.Start()
secondThread.Start()