Skip to main content

The BackgroundWorker is an event-driven way to perform an operation on a separate and dedicated thread, it is mostly used when you need to show the user a friendly progress while you are operating a long running process such as downloading files, connecting to database and getting results…etc.

public partial class BackgroundWorker : Form
{
    public BackgroundWorker()
    {
        InitializeComponent();

        bgWorker.DoWork += BgWorker_DoWork;
        bgWorker.ProgressChanged += BgWorker_ProgressChanged;
        bgWorker.RunWorkerCompleted += BgWorker_RunWorkerCompleted;
    }

    private void btnStartCounting_Click(object sender, EventArgs e)
    {
        progressBar.Maximum = Convert.ToInt32(txtCount.Text);

        lblStatus.ForeColor = Color.Red;
        lblStatus.Text = "Counting...";

        bgWorker.WorkerReportsProgress = true;
        bgWorker.RunWorkerAsync();
    }

    private void BgWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        for (var Counter = 1; Counter <= progressBar.Maximum; Counter++)
        {
            bgWorker.ReportProgress(Counter);
            System.Threading.Thread.Sleep(50);
        }
    }

    private void BgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        lblStatus.ForeColor = Color.Green;
        lblStatus.Text = "Done";
    }

    private void BgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        lblPercent.Text = e.ProgressPercentage.ToString();
        progressBar.Value = e.ProgressPercentage;
    }
}