Results 1 to 40 of 91

Thread: Using the BackgroundWorker Component

Threaded View

  1. #1

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Using the BackgroundWorker Component

    C# version here.

    Create a new Windows Forms project. Add a Label, a ProgressBar and a BackgroundWorker to the form. Set the BackgroundWorker's WorkerReportsProgress property to True. Add the following code then run the project.
    VB.NET Code:
    1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2.     'Raise the DoWork event in a worker thread.
    3.     Me.BackgroundWorker1.RunWorkerAsync()
    4. End Sub
    5.  
    6. 'This method is executed in a worker thread.
    7. Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, _
    8.                                      ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    9.     Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
    10.  
    11.     For i As Integer = 1 To 100
    12.         'Raise the ProgressChanged event in the UI thread.
    13.         worker.ReportProgress(i, i & " iterations complete")
    14.  
    15.         'Perform some time-consuming operation here.
    16.         Threading.Thread.Sleep(250)
    17.     Next i
    18. End Sub
    19.  
    20. 'This method is executed in the UI thread.
    21. Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, _
    22.                                               ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    23.     Me.ProgressBar1.Value = e.ProgressPercentage
    24.     Me.Label1.Text = TryCast(e.UserState, String)
    25. End Sub
    26.  
    27. 'This method is executed in the UI thread.
    28. Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, _
    29.                                                  ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    30.     Me.Label1.Text = "Operation complete"
    31. End Sub
    Last edited by jmcilhinney; Oct 28th, 2008 at 10:49 PM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width