How to use BackgroundWorker in C#.Net

By | 9th September 2017
BackgroundWorker in C# is used to simplify threading. This object is designed to simply run a function on a different thread and then call an event on your UI thread when it’s complete.

 

Illustration code:


1. backgroundWorker1.RunWorkerAsync() :  Used to kickoff the worker thread to begin it’s
DoWork function.

      private void button1_Click(object sender, EventArgs e)
       {
         backgroundWorker1.RunWorkerAsync();
       }



2. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

  {
Write the actual code process here

int perc = 0;

backgroundWorker1.ReportProgress(perc);
}




3. private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgse)
  {

    progressBar1.Value = e.ProgressPercentage;
    }

 

Code in the ProgressChanged event handler is free to interact with UI controls just as with
RunWorkerCompleted. This is typically where you will update a progress bar.

 

4. private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
    {
     MessageBox.Show(“COMPLETED  “, “INFORMATION”, MessageBoxButtons.OK,
MessageBoxIcon.Information);
     }
           this.Close();
     }
RunWorkerCompleted event fires after the DoWork event handler has done its job.