views:

133

answers:

2

We have a business case that would be perfect for multiple BackgroundWorkers.

As an example, we have a form with a "Save" button on it. Normally we would run all the save commands (Save is an example) synchronously and then close the form. We would like to now split the work onto separate threads using backgroundworker.

We will loop through each "Save" required (could be many and/or different number of commands that need executing) creating a BackgroundWorker for each command required.

The question is ... how do we wait for ALL the BackgroundWorkers to complete before we close the form. We understand how to wait for a single BackgroundWorker to complete but when we have X number of BackgroundWorkers operating, how do we wait until all are complete before closing the UI form?

+2  A: 

Track the number of BackgroundWorkers that you've started, decrement the number in the Completed event, and close the form when it reaches 0.

Since the Completed event is raised on the UI thread, you don't need to worry about thread safety.

SLaks
this is a great idea!
washtik
A: 

I'd recommend using the CountdownLatch class presented in the following (very excellent) MSDN Magazine article:

9 Reusable Parallel Data Structures and Algorithms

Bearing in mind SLaks note about BackgroundWorker Completed events being raised on the UI thread, this might be overkill.

spender
You don't need to. BackgroundWorker fires its `Completed` event on the UI thread, so thread-saftey is not a concern.
SLaks
Never used a BackgroundWorker before, so I've learned something today. Does this imply they can only be used in a Forms app?
spender
No; it uses `SynchronizationContext`.
SLaks