The Backgroundworker class provides a simple approach to run time-consuming operations on a background thread. The Backgroundworker class enables you to check the state of the operation and it lets you cancel the operation.
When using of the Backgroundworker class, you can point to operation progress, completion, and cancellation. For example, you can check whether the background operation is completed or canceled and display a message to the user.
1. Create an instance of the Backgroundworker class.
a. Backgroundworker _ backgroundworker = new Backgroundworker();
2. Write the below code where which you want to background operation to allow cancellation and to report progress.
b. _ backgroundworker.WorkerSupportsCancellation = true;
c. _ backgroundworker.WorkerReportsProgress = true;
3. Create an event handler for the background worker's DoWork event. This event is raised when you call the RunWorkerAsync method.
private void _backgroundworker_DoWork(object sender, DoWorkEventArgs e)
4. Create an event handler for the background worker's ProgressChanged event. In this event add code to indicate the progress. This event is raised when you call the ReportProgress method.
private void _backgroundworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
5. Create an event handler for the RunWorkerCompleted event. This event is raised when the DoWork event handler returns.
private void _backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)