Friday, January 13, 2012

Winform Background Thread


The easiest way to implement a background worker thread for a form in a Winform application is to use the BackgroundWorker from the System.ComponentModel namespace.




To summarize the changes imagine you have a form were you dropped a button with the default name 'button1'.


  1. From the toolbox open the component section.

     
  2. Select BackgroundWorker and drag it onto the form.
    1. The default name will be 'backgroundWorker1'.
       
  3. Select the backgroundWorker object and inspect its properties.
    1. Select the Events (it looks like a lightning bolt)
    2. Doubleclick in the space next to 'DoWork'
      1. Keep default name: backgroundWorker1_DoWork
    3. Doubleclick in the space next to 'ProgressChanged'
      1. Keep default name: backgroundWorker1_ProgressChanged
    4. Doubleclick in the space next to 'RunWorkerCompleted'
      1. backgroundWorker1_RunWorkerCompleted

         
  4. Button Click Code Handler
     
    private void button1_Click(object sender, EventArgs e)
    {
    this.backgroundWorker1.RunWorkerAsync("From Form");
    button1.Enabled = false;
    }
     
  5. Background DoWork Handler
     
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
    Thread.Sleep(1000);
    string comment = (string) e.Argument;
    backgroundWorker1.ReportProgress(12, comment + " From Background");
    Thread.Sleep(10000);
    }

     
  6. ProgressChanged Handler


    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    string report = (string)e.UserState;
    listBox1.Items.Add("From Progress Change Hander");
    listBox1.Items.Add(report);
    }
     
  7. RunWorkerCompleted Handler

     
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    button1.Enabled = true;
    }

     




Implementation Versions: This code was developed and tested with Visual Studio 2010, C# 4.0 and the .Net Framework 4 Client Profile.

No comments: