BackgroundWorker Intro Part 1 – Work with ProgressBar

Winform application usually need asynchronous process. Progress status of this process commonly showed with progressbar control.
As a default Thread class accomplish the asynchronous process but .Net has built in BackgroundWorker component to do async easily.

BackgroundWorker component/class has events which are DoWork, ProgressChanged, RunWorkerCompleted.
DoWork handles main async job. ProgressChanged handles displaying async progress info to user. RunWorkerCompleted handles event when async process is completed.

This BackgroundWorker has Cancel ability, so that user can cancel asnyc in the middle of its process.

Lets build one simple application using backgroundworker and progressbar controls.

  1. Create new C# winform application project
  2. Make a form design as below snapshot:
  3. Initialize BackgroundWorker in Form1 Class
    BackgroundWorker bgw;
    
  4. On Form1_Load write
    private void Form1_Load(object sender, EventArgs e)
            {
                bgw = new BackgroundWorker();
                bgw.WorkerReportsProgress = true;
                bgw.WorkerSupportsCancellation = true;
    
                bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
                bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
                bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
            }
    

    We are creating BackgroundWorker instance and set WorkerReportsProgress and WorkerSupportsCancellation property to true to make backgroundworker can report progress and its process can be cancelled.
    Also we declare function to handle its events.

  5. Start Button Click Event:
    private void btnstart_Click(object sender, EventArgs e)
            {
                bgw.RunWorkerAsync();
    
            }
    

    This tells backgroundworker to run asynchronously.

  6. Stop button click event:
    private void btnstop_Click(object sender, EventArgs e)
            {
                bgw.CancelAsync();
            }
    

    Stop button cancels backgroundworker async process.

  7. DoWork event:
     void bgw_DoWork(object sender, DoWorkEventArgs e)
            {
                for (int i = 1; i<=numericUpDown1.Value; i++) {
                    if (bgw.CancellationPending)
                    {
                        e.Cancel = true;
                    }
                    else
                    {
                        bgw.ReportProgress(Convert.ToInt32(i*100/numericUpDown1.Value));
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
    

    We are looping from one to whatever number on numericUpDown1 control. if the process is not cancelled then backgroundworker reporting a percentage progress.
    I use Thread.Sleep function to slow things down in order to test this application. Otherwise when the process is cancelled then e.Cancel=true; will execute, so that backgroundworker is stopping.

  8. ProgressChanged event:
    void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                progressBar1.Value = e.ProgressPercentage;
            }
    

    The percentage progress from bgw.ReportProgress(Convert.ToInt32(i*100/numericUpDown1.Value)); pass to progressBar1 value. progressBar1 now change its value showing a progress occur.

  9. RunWorkerCompleted event:
    void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled == false)
                {
                    MessageBox.Show("Done");
                }
                else
                {
                    MessageBox.Show("Cancelled");
                }
            }
    

    When async process has done or cancelled this event execute.

  10. Run this project.

If you want to take a look at Asp .Net Ajax BackgroundWorder please browse this link: ASP .Net Ajax BackgroundWorker Example Using Client Script & PageMethods

Regards,
Agung Gugiaji

Advertisements

2 responses to “BackgroundWorker Intro Part 1 – Work with ProgressBar

  1. Pingback: Fill DataGridView and cancel process using DataAdapter and BackgroundWorker | Enlighten Application Developer Journals

  2. Pingback: BackgroundWorker Part 2 – Reporting Class Instance Status (C#) | Enlighten Application Developer Journals

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s