article

Basic Free Threading

Email
Submitted on: 1/2/2015 1:15:00 AM
By: Petko Petkov (from psc cd)  
Level: Beginner
User Rating: By 4 Users
Compatibility: VB.NET
Views: 775
 
     Basic Free Threading

 
				

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


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.