Archive

Posts Tagged ‘Threading’

Using background worker in C#

August 19th, 2009 Anuraj P 2 comments

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