Home > .Net, .Net 3.0 / 3.5, Visual Studio, Windows Forms > Using background worker in C#

Using background worker in C#

Background worker is a component introduced by Microsoft in .Net 2.0 which will help developers to do background operations without the knowledge of threading and deadlocks. In the current application I am working we used to copy some files from hard drive to specified USB drive, based on some criteria. For the IO operation we used some background worker, but for the progress reporting we used a very easy method, we just put a progress bar and set the Style property to Marquee. It will display a block moving always from right to left. We were aware of the ProgressChanged event, but when I tried it, it throws some cross thread exception. After working around the documentation in MSDN I found the solution for this.

Example Code

Make sure the background worker WorkerReportProgress Property set to


//BackGround Worker DoWork Event.
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Do the long running job here
int index = 0;
while(true)
{
	if(index >= 100)
	{
		break;
	}
	index ++;
	Thread.Sleep(100);
	//The second parameter is required only
	//if you want to display some output
	//Here we are updating the Progress.
	this.bgWorker.ReportProgress(index, index);
}
}

//BackGround Worker Progress Changed Event.
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
	this.pbStatus.Value = e.ProgressPercentage;
	this.lstValues.Items.Add(e.UserState);
}

//BackGround Worker Work completed Event.
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
	MessageBox.Show("Successfully completed");
}

In this code, I am counting from 0 to 100, also updating a Progress bar and Listbox in Userinterface with the values.

Links :
Back Ground worker in MSDN

  1. Ciapa
    September 5th, 2009 at 03:31 | #1

    how we get the data from textBox (input data) using Backgroundworker ?

  2. September 5th, 2009 at 13:05 | #2

    Hi, Sorry I can’t understand the question. Why we need a background worker to get data from textbox? Can explain more. It will be helpful.

    thanks
    Anuraj

  1. No trackbacks yet.