Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Framework  »  Framework 2.0  »  Multithreading The Easy Way: The BackgroundWorker  »  Getting Started - DoWork
 »  Home  »  .NET Framework  »  Framework 3.0  »  Multithreading The Easy Way: The BackgroundWorker  »  Getting Started - DoWork
 »  Home  »  .NET Intermediate  »  Multithreading The Easy Way: The BackgroundWorker  »  Getting Started - DoWork
 »  Home  »  Visual Studio 2005  »  Multithreading The Easy Way: The BackgroundWorker  »  Getting Started - DoWork
 »  Home  »  Visual Studio 2008  »  Multithreading The Easy Way: The BackgroundWorker  »  Getting Started - DoWork
 »  Home  »  Windows Development  »  Visual Basic 2005  »  Multithreading The Easy Way: The BackgroundWorker  »  Getting Started - DoWork
 »  Home  »  Windows Development  »  Windows Presentation Foundation  »  Multithreading The Easy Way: The BackgroundWorker  »  Getting Started - DoWork
Multithreading The Easy Way: The BackgroundWorker
by Ged Mead | Published  06/01/2008 | Framework 2.0 Framework 3.0 .NET Intermediate Visual Studio 2005 Visual Studio 2008 Visual Basic 2005 Windows Presentation Foundation | Rating:
Getting Started - DoWork

  To follow along with this example, start a new Windows Forms project and drag a BackgroundWorker component from the Toolbox on to the form.

  Copy and paste the code from the previous page into the form's code file.  Note that you will also need to add an Imports statement at the top of the file:

 Code Copy

Imports System.IO

   I have named my demo BackgroundWorker:  bWkrFileCheck.

   In the Properties Window for this BackgroundWorker you will see that there are only a few properties.  Two of them - WorkerReportsProgress and WorkerReportsCancellation -  have a default setting of False.

  In order for you to be able to write working code that gives user feedback and allows the background process to be aborted, you need to set both these properties to True.

Properties Window

   For this first stage you will also need to add a button to the form.   I have named this button:   btnStart.

   When you click on this button, code will be fired which instructs the BackgroundWorker to begin carrying out whatever task(s) it has been allotted.

   So the code to place in the button's click event is:

Code Copy
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click

        bWkrFileCheck.RunWorkerAsync()

End Sub

     The RunWorkerAsync method is a fairly self-explanatory one which means that it goes off and finds the task that bWkrFileCheck has been assigned and carries it out asynchronously.  That is, it works separately.  And in this context working separately means that the task is undertaken on a separate thread.

   If you add the button and enter the above code and run the project, you should see .... well, nothing, actually!   Hopefully, not an Exception message, but also no sign of any activity either.  

   And in fact there is no activity to monitor, because we haven't yet told the BackgroundWorker specifically what its task is.   That task of course will be to run the file search routine we entered previously, the "FileFinder" procedure.

  The place where we specifically tell the BackgroundWorker what task it has been assigned is in its DoWork event.  As with the list of properties you saw above, the list of events of a BackgroundWorker is fairly sparse; DoWork being the most fundamental one.

 

Properties Window

 

  In this first stage, the code for the DoWork event will be:

 

Code Copy
  Private Sub bWkrFileCheck_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bWkrFileCheck.DoWork

        FileFinder("C:\Program Files\")

  End Sub
 
      which is basic code that calls the FileFinder procedure and passes in a target folder as its argument.  
 
  If you want to  check that this works so far, then change the code of the FileFinder sub so that it writes the file names to the output window:
 
 
 
Code Copy
For Each fname As String In Directory.GetFiles(dir)
       If fname.EndsWith("txt") Then
            Console.WriteLine(fname)
        End If
Next
 
     If you run this, you will see that the task has been properly handed off to the BackgroundWorker and while that task is visibly running you can still do other things with your form, such as move it or resize it.   We'll improve the demo in the next few steps.
 
   So, even at this early stage we now have a second process running on a separate thread, so allowing the user to continue doing other things.  But of course it would be much better if we were to give some kind of feedback on how much progress the task has made.
 
   That will be our next step.
 
Comments    Submit Comment

Comment #1  (Posted by an unknown user on 06/04/2008)
Rating
Very clear and easy to follow. AND the sample Worked!!!!
 
Comment #2  (Posted by RAB on 06/12/2008)
Rating
Can we use teh Backgroundworker component without a form? Can it be instantiated in a module?
 
Comment #3  (Posted by Ged Mead on 06/20/2008)
Rating
Yes you can do that. However as there is no toolbox available for a Module you have to create the bgw in code. To do this you use Dim bgw as New System.ComponentModel.BackgroundWorker.
You will of course also need to set the properties and add handlers in code.
If you need more info on this question please post a question in the vbcity VB.NET forums (where it's easier for me to post code samples) :-}
 
Comment #4  (Posted by an unknown user on 07/30/2008)
Rating
Thank a lot XTab
 
Comment #5  (Posted by an unknown user on 08/08/2008)
Rating
Great step-by-step with in-line code. Ged obviously put alot of time in this well written article.
More please !
 
Comment #6  (Posted by an unknown user on 08/13/2008)
Rating
I try to read everything you publish. Great stuff.
 
Comment #7  (Posted by an unknown user on 08/18/2008)
Rating
Excellent and simple to use.
 
Comment #8  (Posted by an unknown user on 09/06/2008)
Rating
practical, readable
 
Comment #9  (Posted by an unknown user on 09/29/2008)
Rating
This guide was one of the best guides I've read!

You just helped me understand something I origionally had no clue about. Thanks!
 
Comment #10  (Posted by Matt Higginbotham on 10/31/2008)
Rating
Thanks Ged! What a great article.. This helped me a bunch with some long database queries that i have.

Keep Em' Coming
 
Comment #11  (Posted by an unknown user on 11/03/2008)
Rating
Very good except the cancelation did not work correctly, although it cancelled the task if I cancelled it and then re-ran I got "Operation has already had OperationCanceled called on it". I need to reset the canelled property at finish but, its read only any ideas?
 
Sponsored Links