re: Swift: Easy way to wait for multiple background tasks to finish VIEW POST


One thing though, is that relying on DispatchGroup - while being great - does not allow to control the number of threads that will be created on the queue. It can lead to thread explosion depending on the job done by the work items. If you have many tasks that should run in parallel, you need to take this into account and maybe use a OperationQueue instead. Using dependent operations on an OperationQueue, you can also wait for all operations to finish before continuing.


Thank you for the additional insight. I thought DispatchQueue is pretty smart when it comes to handling threads and generally you dont have to worry about it.. Would love to read more about OperationQueue if you have more thoughts & tips to share!


Well it depends. If your work that is dispatched does not seem to make enough progress, the OS might decide to spawn more threads and you could hit that soft limit and the app could crash. Probably never in your use case where you download a few files. But my use case is a collection of several 10,000 files that need to be accessed for metadata in the background. I used a DispatchGroup to wait for everything to complete before moving to the next step but I was hit hard by thread explosion. Randomly. I moved to NSOperationQueue and added a limit on the number of concurrent operations. There is also a lesser known command called DispatchQueue.performConcurrent(...) that is useful and will limit the number of threads to 8.
This article, albeit a bit old, is good: agostini.tech/2017/08/20/dispatchg...

code of conduct - report abuse