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.
- Skill level:
Other People Are Reading
Things you 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:
"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 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.
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
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.
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 and 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.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for