Windows Forms: BackgroundWorker in C#

By FoxLearn 6/1/2017 8:14:19 PM   6.96K
How to use a Background Worker in C#. The Background Worker class allows you to run an operation on a separate, dedicated thread.

When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "BackgroundWorkerExample" and then click OK

backgroundworker in c#Step 2: Design your form as below

backgroundworker in c#

Step 3: Add a click event handler to the button

struct DataParameter
{
    public int Process;
    public int Delay;
}

private DataParameter _inputparameter;

//Update progress bar
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progress.Value = e.ProgressPercentage;
    lblPercent.Text = string.Format("Processing...{0}%", e.ProgressPercentage);
    progress.Update();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    //Set parameter
    int process = ((DataParameter)e.Argument).Process;
    int delay = ((DataParameter)e.Argument).Delay;
    int index = 1;
    try
    {
        for (int i = 0; i < process; i++)
        {
            if (!backgroundWorker.CancellationPending)
            {
                backgroundWorker.ReportProgress(index++ * 100 / process, string.Format("Process data {0}", i));
                Thread.Sleep(delay);//used to simulate length of operation
                //Add your code here...
            }
        }
    }
    catch (Exception ex)
    {
        backgroundWorker.CancelAsync();
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    MessageBox.Show("Process has been completed.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

//Run backgroundworker
private void btnStart_Click(object sender, EventArgs e)
{
    if (!backgroundWorker.IsBusy)
    {
        _inputparameter.Delay = 10;
        _inputparameter.Process = 1200;
        backgroundWorker.RunWorkerAsync(_inputparameter);
    }
}

private void btnStop_Click(object sender, EventArgs e)
{
    if (backgroundWorker.IsBusy)
        backgroundWorker.CancelAsync();
}

VIDEO TUTORIALS