README.md
December 4, 2022 · View on GitHub
Description
Basic Free Threading
More Info
| Submitted On | |
| By | Petko Petkov |
| Level | Beginner |
| User Rating | 5.0 (20 globes from 4 users) |
| Compatibility | VB.NET |
| Category | System Services/ Functions |
| World | .Net (C#, VB.net) |
| Archive File |
Source Code
Free Threading
For the first time, VB.NET has given VB developers the ability to write truly
freethreaded
applications. If your application is going to perform a task that could take
a
long time, such as parsing through a large recordset or performing a complex
series
of mathematical calculations, you can push that processing off to its own thread
so
that the rest of your application is still accessible. In VB6, the best you
could do to
keep the rest of the application from appearing to be locked was to use the
DoEvents
method.
Examine this code, which is written for VB.NET. Here you have some code for
button1. This code calls the BeBusy routine, which has a loop in it to just
to take up
time. However, while in this loop, you are consuming the thread for this application,
and the UI will not respond while the loop is running.
Open a new VB project. Add a button.
Private Sub button1_Click(ByVal
sender As System.Object, _
ByVal e As
System.EventArgs) Handles button1.Click
BeBusy()
End Sub
Sub BeBusy()
Dim i As Decimal
For i = 1 To
20000000
‘do nothing but
tie up app
Next
Beep()
End Sub
To create a thread, you must use the System.Threading.Thread class.
Imports System.Threading.Thread
To fix the code and keep BeBusy from consuming the main program thread, you
have
now created a new thread and will run BeBusy on that thread. However, that line
of
code isn’t enough. Next, you must call the Start method on that new thread.
With
VB.NET, calling BeBusy on its own thread would look like this:
Private Sub button1_Click(ByVal
sender As System.Object, _
ByVal e As
System.EventArgs) Handles button1.Click
'Creatre a new thread
Dim busyThread As
New System.Threading.Thread(AddressOf BeBusy)
busyThread.Start()
End Sub