Be Careful Using DispatchGroups with Fast Running Code

Joe Susnick
2 min readFeb 7, 2018

A short lesson in something that can go wrong.

A lot of the code online about DispatchGroup and how to use it is a bit misleading. Many examples look something like this:

Feel free to run this in a playground. After three seconds you’ll see:

leaving first group after 3 seconds
leaving second group after 3 seconds
finished

This is fine. It shows you how to enter and leave a DispatchGroup and how to delay code from running using DispatchQueue's asyncAfter method. Normally this is fine. You’ll have slow running network calls and you’ll have time to enter the next group before the first finishes running.

Let’s use a shopping cart metaphor. Before you show a user a shopping cart you want to make sure they’re signed in and you want to check if they added items to their cart on the website.

How not to add items to a cart.

In this metaphor the first item of work is nearly instantaneous. Maybe you’re hitting UserDefaults or the device’s keychain or something. It’s almost instantaneous but not quite.

The second item of work is likely to take a little longer. You probably need to hit some service and it may take significantly longer than the first piece of work.

This will output:

leaving first group almost immediately
finished
leaving second group after 3 seconds

To continue the metaphor, we’ll be showing the shopping cart before we have items to display. If we’ve mishandled capture groups then this could even crash the app. 😱 😱 😱 😱 or maybe, 😭 😭 😭 😭.

My recommendation is to either be very very careful, or safer yet, to be diligent about entering work items near where the DispatchGroup is defined. That approach looks like this:

And correctly outputs:

leaving first group almost immediately
leaving second group after 3 seconds
finished

This is a bit of overhead to preempt an edge case but edge cases are important. I’ll leave you with one of my favorite quotes.

“Take care of the corners and the room takes care of itself” — Frank Lloyd Wright (unconfirmed)

As always, please let me know if this was helpful or if I managed to miss the point entirely. :D Thanks!

--

--