Let us learn BackgroundWorker class

Niladri.Biswas
Posted by in Windows Forms category on for Beginner level | Points: 250 | Views : 3162 red flag

In this article we will learn about BackgroundWorker class


 Download source code for Let us learn BackgroundWorker class

Introduction

Whenever we try to do some long running operation on the UI without freezing it, we need to run it in a separate thread.In this article we will look into the BackgroundWorker class , as one of the various solutions to this problem with a simple example. BackgroundWorker executes an operation on a separate thread and provide a notification to UI Thread whenever necessary.

Straight To Experiment

Let us create a UI as under

The objective is that,when we will click on the "Populate" button, at the same time we should be able to write something in the "Textbox".

Now let us look into the code which is without BackgroundWorker

public partial class WithOutBackgroundThread : Form
{  
	List<Employee> lstEmp;

	public WithOutBackgroundThread()
	{
		InitializeComponent();
		lstEmp = new List<Employee>();
	}

	private void btnPopulate_Click(object sender, EventArgs e)
	{  
		GetEmployeeRecords();
		dataGridView1.DataSource = lstEmp;
		lblStatus.Text = "Work Completed";
	}

	//Prepare the data
	private void GetEmployeeRecords()
	{
		for (int i = 1; i <= 10; i++)
		{
			// Simulate a pause
			Thread.Sleep(1000);
			lstEmp.Add(new Employee { EmpId = i, EmpName = "Name" + i });
		}
	}
}

The code is pretty straightforward.In the "GetEmployeeRecords()" method, we are preparing the data.We have introduce the "Thread.Sleep(1000)" to make a delay. And in the "Populate" button click event, we are populating the Gird.

But if we execute this code, the UI will become unresponsive and henceforth, we cannot perform any task on the "Textbox" which is our objective.

Henceforth let us change our code to the below

public partial class WithBackgroundThread : Form
{
	BackgroundWorker workerThread;
	List<Employee> lstEmp;

	public WithBackgroundThread()
	{
		InitializeComponent();

		lstEmp = new List<Employee>();
		workerThread = new BackgroundWorker();
		workerThread.DoWork += new DoWorkEventHandler(workerThread_DoWork);
		workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workerThread_RunWorkerCompleted);

	}

	private void btnPopulate_Click(object sender, EventArgs e)
	{
		workerThread.RunWorkerAsync(); 
	}

	private void workerThread_DoWork(object sender, DoWorkEventArgs e)
	{
		GetEmployeeRecords();
	}

	private void workerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
	{
		lblStatus.Text = "Work Completed";
		dataGridView1.DataSource = lstEmp;
	}

	//Prepare the data
	private void GetEmployeeRecords()
	{
		for (int i = 1; i <= 10; i++)
		{
			// Simulate a pause
			Thread.Sleep(1000);
			lstEmp.Add(new Employee { EmpId = i, EmpName = "Name" + i });
		}
	}
}

A lot of new things.We will explore one by one.

First, we need to declare BackgroundWorker Thread

BackgroundWorker workerThread = new BackgroundWorker();

Next,we need to subscribe to the events

workerThread.DoWork += new DoWorkEventHandler(workerThread_DoWork);
workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workerThread_RunWorkerCompleted);

As a third step, we need to implement the two methods

private void workerThread_DoWork(object sender, DoWorkEventArgs e)
{
   // run all background tasks here
   GetEmployeeRecords();
}

private void workerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete its work
  lblStatus.Text = "Work Completed";
  dataGridView1.DataSource = lstEmp;
}

The "DoWork" event is raised when we call the "RunWorkerAsync" method. This is where we start the operation that performs the potentially time-consuming work.The "RunWorkerCompleted" event is fired when the background operation has completed, has been canceled, or has raised an exception

As a last step, invoke the "RunWorkerAsync" from the "Populate" button click event.

private void btnPopulate_Click(object sender, EventArgs e)
{
	workerThread.RunWorkerAsync(); 
}

The "RunWorkerAsync" starts execution of a background operation.

Now if we run our application we will be able to populate the grid as well as write something on the "Textbox".

References

Conclusion

Hope this article has explained the concept of BackgroundWorker clearly.Thanks for reading the article.Zipped file is attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)