How to Thread in VB.Net

104 30

    Start Visual Basic

    • 1). Start a new Windows Form Application project in Visual Basic .NET giving it an appropriate name, something like "VB Thread Example." This will create a new application for you with one main form.

    • 2). Switch to the code behind for the main form and add "Imports System.Threading"

      at the very top. This imports the ".net" namespace needed for working with threads.

    • 3). Create the routine that will be the thread task. Here is a simple example that simply counts from 0 to 10000:

      Public Sub LongProcess()

      Dim Index As Integer

      For Index = 0 To 10000

      Application.DoEvents()

      Next

      MsgBox("Thread Completed")

      End Sub

      This will simulate the long running process. Long calculations for slow database calls would be good candidates to enclose in one routine that can then be threaded.

    • 4). Add a button to the form and in it's click handler start the task:

      Dim t As Thread

      t = New Thread(AddressOf LongProcess)

      t.Start()

      MsgBox("Program Completed")

      Take particular notice of the placement of the MsgBox commands. Sequential programming would imply that the "Thread Completed" would be the first message box to appear. As you see when the program is run, this isn't the case.

    • 5). Run the "VB Thread Example" program and click on the button on the form. Notice that the "Program Completed" message box appears first. This is because the program "spawned" the thread that is still working; when it is finished it's message box will appear. Make the counter go higher to increase this delay.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.