Example of multithreading in VB.NET


In this article, I am providing an example of Multithreading in VB.NET.Multithreading is basically doing multiple tasks at a time. But, in fact it is not done at a time in the processor. We get a feeling that it is done at the same time.

I wanted to give you a very simple example of multithreading here. I am writing this article because even though I saw a number of examples in many places, I was not able to compile and run that due to errors arising from the program. So when I at last found the answer, I thought of sharing it.

Multithreading is basically doing multiple tasks at a time. But, in fact it is not done at a time in the processor. We get a feeling that it is done at the same time.

Open a new Project in VB.NET and thus a form will be created.


Imports System.Threading

Public Class Form1

Private _threadOutput As String = ""
Dim _stopThreads As Boolean = False

Private Sub DisplayThread1()
While _stopThreads = False
MessageBox.Show("Display Thread 1")
_threadOutput = "Hello Thread1"
Threading.Thread.Sleep(1000)
MessageBox.Show("Thread 1 Output --> {0}", _threadOutput)
End While
End Sub

Private Sub DisplayThread2()
While _stopThreads = False
MessageBox.Show("Display Thread 2")
_threadOutput = "Hello Thread2"
Threading.Thread.Sleep(1000)
MessageBox.Show("Thread 2 Output --> {0}", _threadOutput)
End While
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
MessageBox.Show("hi")
Dim thread1 As Threading.Thread = New Threading.Thread(New ThreadStart(AddressOf DisplayThread1))
Dim thread2 As Threading.Thread = New Threading.Thread(New ThreadStart(AddressOf DisplayThread2))

thread1.Start()
thread2.Start()

End Sub
End Class



The code above is a sample of multithreading. You could see that even two messageboxes may appear at a time. It is because the processor will not wait for one task to complete to start the another. Both the functions are started at the same time and thus gives us results at the same time.

Even though threading is a bit complex to program, it makes the application a lot faster.

This is just a sample. You could get more theory on multithreading from various sources.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: