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:
"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
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
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
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.
- Photo Credit Kutay Tanir/Photodisc/Getty Images
How to Create a Function Button in Visual Basic
As Visual Basic is a main driver of web programming technology, it makes sense to figure out the basics of the language....
How to Run a Visual Basic Program on a PC
Like C++, C Sharp and Java, Visual Basic (VB) is an object oriented programming language. Recently it was integrated to the Microsoft...
How to Check for a Process in Visual Basic
Microsoft Visual Basic is a powerful programming language yet is easy to use. Various features and functionality are available to build many...
How to Use a Subroutine in Excel Visual Basic
Microsoft Excel's programming language, Visual Basic for Applications (VBA), is a powerful tool that is accessible to anyone, including non-programmers. With macros...
How to Program an Excel Spreadsheet to Auto Update From the Web
Creating an Excel spreadsheet to update automatically from the Internet can be highly beneficial if you wish to keep track of stock...