How to Run Visual Basic Subroutine in the Background


When a computer program needs to perform a long drawn-out subroutine, it is best to have it execute the subroutine as a background thread. A background process normally does not have the same priority as a user interface process, so it will execute more slowly. Subroutines may include checking for and downloading updates, transferring log files or performing long calculations.

Things You'll Need

  • Visual Basic
  • Start Visual Basic and create a new project of the Windows form project type.

  • Make the first line of the code file:

    "Imports System.Threading"

    And add:

    "Dim t As Thread"

    to the main class in the form.

  • Add a button to the form and change its name to "btnStart." Change the button's text property to "Start Background Process."

  • Add the following code to the "btnStart" click action:

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click

    t = New Thread(AddressOf Me.BackgroundProcess)

    t.Priority = ThreadPriority.BelowNormal ' This will push the subroutine even further into the background


    End Sub

    This routine will start a process in the background and give it a lower than normal priority so it will run a little more slowly and not interfere with the user interface elements.

  • Add the subroutine is to be run in the background:

    Private Sub BackgroundProcess()

    ' Do a long process here, not just an infinite loop

    Do While True


    End Sub

  • For thoroughness, add the following code to the forms closing method:

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing


    End Sub

    Without this routine, the program won't exit normally because the thread will still be running.

  • Run the program and click on the only button on the form. This will start the process that is to run in the background.

Tips & Warnings

  • Be sure to keep everything in the subroutine to be run in the background very isolated. Without using more advanced threading techniques, it is not possible to know what is happening at any given time.

Related Searches


  • Photo Credit Kutay Tanir/Photodisc/Getty Images
Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!