Reputation: 225
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?
Upvotes: 2
Views: 697
Reputation: 120400
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.
Upvotes: 0
Reputation: 887305
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.
Upvotes: 2