How to Run Visual Basic Subroutine in the Background

How to Run Visual Basic Subroutine in the Background thumbnail
Background subroutines are good for doing long processes.

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
Show More

Instructions

    • 1

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

    • 2

      Make the first line of the code file:

      "Imports System.Threading"

      And add:

      "Dim t As Thread"

      to the main class in the form.

    • 3

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

    • 4

      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

      t.Start()

      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.

    • 5

      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

      Loop

      End Sub

    • 6

      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

      t.Abort()

      End Sub

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

    • 7

      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:

References

  • Photo Credit Kutay Tanir/Photodisc/Getty Images

Comments

You May Also Like

Related Ads

Featured