JavaScript Error

You currently have JavaScript disabled on your web browser.

This website uses JavaScript, and This web page needs JavaScript activated to work correctly.

Please active JavaScript on your web browser and then refresh this web page.



BackgroundWorker



example0

The BackgroundWorker component is found in the System.ComponentModel namespace within the System.ComponentModel.EventBasedAsync.dll.

The purpose and function of a BackgroundWorker component is for performing non-graphical operations on a separate dedicated thread, that run silently in the background. While the BackgroundWorker components process is performing its operations, the user is free to continue using the rest of the program without having to first wait for the BackgroundWorker to complete its process. Any number of BackgroundWorker components can run simultaneously, and each will run on their own separate thread.

The BackgroundWorker component can be found in the Controls Toolbox window panel within the Forms editor screen. Even though the BackgroundWorker component is located in the Controls Toolbox, it is best to think of this object as a component and not as a control simply because it has no graphical user interface, and therefore it is not visible on the form itself.

Some example uses of the BackgroundWorker include, but are not limited to, checking for software updates across servers, checking if user is connected online, getting latest chat messages from a server someplace, auto-saving the users progress, etc...


Example Source Code

This example uses a BackgroundWorker component, along with a NumericUpDown control, two Button controls, two Label controls, and a ProgressBar control.

The following is an example of beginning the BackgroundWorker process with a button click event, perform some long operation in the background, reporting its progress to update a progress bar on the form, and handle any cancel requests from the user.

To add the BackgroundWorker component to your form, double click on its name as listed in the Toolbox window panel. Alternatively, you can single click on it and then drag and drop it onto your form. Once it is added, it will appear in a window located below the form, since it has no user interface and will not actually appear on the form itself.

Once it is added, then you can view and adjust its properties in the Properties window. Set the WorkerReportsProgress and WorkerSupportsCancellation properties to True:

properties

Then click the events icon to view the available events. Double click on each of the three available events to auto-generate their event callback functions.

events

Build the rest of the form by adding Labels, NumericUpDown, Buttons, and a ProgressBar to the form.

The form should now look like this:

form1

The source code for this example is as follows:

 
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestProgram
{
    public partial class Form1 : Form
    {
        public int currentValue;
        public int targetValue;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // set background worker values
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;

            // set numericUpDown control values
            numericUpDown1.Minimum = 0;
            numericUpDown1.Maximum = int.MaxValue;
            numericUpDown1.Value = 1000;

            // init default values
            setDefaultValues();
        }

        private void setDefaultValues()
        {
            // init everything with default values
            currentValue = 0;
            targetValue = (int)numericUpDown1.Value;
            label1.Text = "0";
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy != true)
            {
                // re-init default values
                setDefaultValues();

                // start the background process
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            // cancel and stop the background process
            if (backgroundWorker1.WorkerSupportsCancellation == true)
            {
                backgroundWorker1.CancelAsync();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // loop from 0 to targetValue
            int currentPercent = 0;
            for (int n=0; n < targetValue; n++)
            {
                // set current value
                currentValue = n;

                // check if user requested cancel
                if(worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                // calculate percent completed
                currentPercent = (int)(((double)n / (double)targetValue) * 100);

                // report progress
                backgroundWorker1.ReportProgress(currentPercent);

                /* for demo purposes lets slow things down by
                waiting a fraction of a second before continuing */
                System.Threading.Thread.Sleep(50);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // update the label
            label1.Text = currentValue.ToString();

            // update the progress bar
            progressBar1.Value = e.ProgressPercentage;

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // see why work completed
            if(e.Error != null)
            {
                // an error happened
                label1.Text = "Error: " + e.Error.Message;
            }
            else if(e.Cancelled == true)
            {
                // user had cancelled
                label1.Text = "User Cancelled at interval # " + Convert.ToString(currentValue);
            }
            else
            {
                // process completed
                label1.Text = "Process Completed at interval # " + Convert.ToString(currentValue);
            }

            // clear the progress from the progress bar
            progressBar1.Value = 0;
        }

    }
}


Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.


(0) pollYesResult
(0) pollNoResult



 
     About   |   Contact Us   |   Privacy   |   Terms & Conditions   |   © 2024 - T&J Divisions, LLC, All Rights Reserved