Monthly Archives: February 2014

BackgroundWorker Part 2 – Reporting Class Instance Status (C#)

About long time ago, I already wrote about basic of BackgroundWorker component, BackgroundWorker Part 1.
It contained simple example on how to use BackgroundWorker and also ProgressBar. If you want to look then go to this url

This part 2 will go for more advance implementation example. This means application itself is simple but its coding technique is more advance.

As you may know by now that BackgroundWorker makes procedure run asynchronously. For example I have a procedure to run and the progress change of running procedure is reported.
This is possible because of this procedure run asynchronously by BackgroundWorker.

In order to run a BackgroundWorker, we have to use DoWork event handler function. So we need to write a procedure we want inside that DoWork function.
Most of examples show how to just write a whole codes in DoWork. For example below code:

void backgroundworker1_DoWork(object sender, DoWorkEventArgs e)
	{
		for (int i = 1; i <= numericUpDown1.Value; i++)
		{
			if (backgroundworker1.CancellationPending)
			{
				e.Cancel = true;
			}
			else
			{
				backgroundworker1.ReportProgress(Convert.ToInt32(i*100/numericUpDown1.Value));
				System.Threading.Thread.Sleep(100);
			}
		}
	}

So it shows simple looping and send its report progress but the whole iteration coding is inside DoWork. When more complex requirement is needed then the coding become cumbersome.

We need a way to separate main procedure from DoWork function. So, it will also make loose coupling.
This procedure inside DoWork must have asynchronous capability. To accomplish this, I use Thread object. Thread will make asynchronous process.
Continue reading

Advertisements