Wait for BackgroundWorker process

less than 1 minute read

Let’s say your class is BackgroundWorker and you have a child class who is another BackgroundWorker. If a cancellation is requested from user, you want to cancel both child and parent BWs. Here is the code, assume that this is the parent class.

private ManualResetEvent mre = new ManualResetEvent(false);

void startBW() {
	BW = new BW(); //BW is BackgroundWorker class
	BW.RunWorkerCompleted += BW_RunWorkerCompleted;
	BW.ProgressChanged += BW_ProgressChanged;

	//wait until it finishes

void BW_ProgressChanged(object sender, ProgressChangedEventArgs e)
	//if cancellation is pending in this thread, notify the child BW
	if (CancellationPending)

void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
	//when everyting is set, raise flag so that execution will continue.

What happens is you declare a ManualResetEvent which can block current thread to wait until an event has occurred. This variable is controlled by child, when it finishes, in RunWorkerCompleted method, flag is raised. At each progress step, CancellationPending is checked in parent class, if so, child class is being notified.



Leave a Comment