Saturday, May 12, 2007

Add Multithreading to your VB.NET Applications

VB.NET natively supports free threaded applications. In plain English, this means you can split up your application into multiple threads so that it can do different things at the same time.

There are many situations in which spawning a new thread to run in the background will make your application more responsive and increase its usability. Consider the following example:

Public Class Form1
Private sMessage As String

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub

Private Sub CountUp()
Dim I As Integer
For I = 1 To 10
sMessage = "Iteration #: " & I
End Sub
End Class

In this simple example, we are just counting from 1 to 10. Note that when each counter is increamented the computer would wait 2 seconds before process the next instruction. So when the routine CountUp is invoked, it would run for approximately 20 seconds. During that time, your application can't do anything else thus you can't click on Button1 to see the message.

To execute code in a thread, we need to use the Thread object that is a part of the System.Threading namespace in the .NET framework classes. The first thing we need to do is to instantiate a new Thread object and pass to it the address of the code block we want to run under the thread and then invoke the Start method.

The example above could be modified as below:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myThread As System.Threading.Thread
myThread = New System.Threading.Thread(AddressOf CountUp)
End Sub

Now when you run the application again, it will be more responsive and if you keep clicking on Button1, you will see the message changes as the application runs.

No comments: