Results 1 to 4 of 4

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

    VB 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.
    CSharp Code:
    1. private void Form1_Load(object sender, EventArgs e)
    2. {
    3.     // Raise the DoWork event in a worker thread.
    4.     this.backgroundWorker1.RunWorkerAsync();
    5. }
    6.  
    7. // This method is executed in a worker thread.
    8. private void backgroundWorker1_DoWork(object sender,
    9.                                       DoWorkEventArgs e)
    10. {
    11.     BackgroundWorker worker = (BackgroundWorker)sender;
    12.  
    13.     for (int i = 1; i <= 100; i++)
    14.     {
    15.         // Raise the ProgressChanged event in the UI thread.
    16.         worker.ReportProgress(i, i + " iterations complete");
    17.  
    18.         // Perform some time-consuming operation here.
    19.         System.Threading.Thread.Sleep(250);
    20.     }
    21. }
    22.  
    23. // This method is executed in the UI thread.
    24. private void backgroundWorker1_ProgressChanged(object sender,
    25.                                                ProgressChangedEventArgs e)
    26. {
    27.     this.progressBar1.Value = e.ProgressPercentage;
    28.     this.label1.Text = e.UserState as string;
    29. }
    30.  
    31. // This method is executed in the UI thread.
    32. private void backgroundWorker1_RunWorkerCompleted(object sender,
    33.                                                   RunWorkerCompletedEventArgs e)
    34. {
    35.     this.label1.Text = "Operation complete";
    36. }
    Note that if you paste that code into your own form you'll need to go to the Properties window in the designer to attach the event handlers for it to work.
    Last edited by jmcilhinney; Oct 28th, 2008 at 01:26 AM.
    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