Writing Multithreading codes in VB.NET
Implementing multithreading to your application is in fact very easy and simple. We will go through the example below to understand how multithreading works. Firstly, before you do anything, you have to include the namespace below into your project. Add it at the top of your project module.
Imports System.Threading.Thread
Next, you will have to add a BackgroundWorker component from the toolbox into your project as show below.

Then, add the 4 controls as shown in the figure below into an empty form and name them as follows.
BtnMT, BtnNonMT, TextBox1, ProgressBar1

After that, add the following codes (Copy & Paste) into your project.
Public Sub StartBackgroundWorker()
If BackgroundWorker1.IsBusy = True Then
MsgBox("Process already running, please wait.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
Else
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Protected Overridable Sub BackgroundWorkerJob_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
RunCount()
End Sub
Private Sub BackgroundWorkerJob_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.Text = "Process is running, Please Wait!"
End Sub
Protected Overridable Sub BackgroundWorkerJob_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Me.Text = "Process Finished."
End Sub
Private Sub RunCount()
Dim i As Integer
For i = 1 To 100
Sleep(500)
TextBox1.text = i & "%"
ProgressBar1.Value = i
Next
End Sub
Finally, add this code behind BtnMT button
Me.StartBackgroundWorker()
and this code behind BtnNonMT button
RunCount()
Now, start the application and click on MT button. Notice the result in the diagram below. While the separate thread is running the lengthy process, the user interface shows the progress and the TextBox1 shows the percentages completed.
Now, lets re-run the application and click on Non MT button this time. Both the lengthy process and the user-interface will be running under the same thread. See the result in the diagram below. Notice that without multithreading, the application stops responding after a while with the message showing Form1(Not Responding). Worst still, the application simply forgot to show the percentage completed in the TextBox1. Now, the user will have a hard time to know exactly when the process is going to finish.
Hope this simple multithreading example that i have created above helps you understand and let you know the difference between multithreading and non-multithreading applications.
Back To MultiThreading in VB.NET



0 comments
Post a Comment