How and why does the dispatchgroup.notify method get called before all the entered instances have left?
I tried adding the dispatchGroup.enter within the same loop and the output is the same.
Theoretically it should have exited before anything executes at all.
What environment. was your code running in?
The code I wrote was tested by adding it into the standard app template on the main thread. If you were running in a playground, I think you basically end up replicating a very similar environment. We don't actually "say" this, but I believe the playground basically runs all code inside an implicit runloop, since that ensure that more of our APIs "work".
Note that if you simply add that into a command line tool, what will actually print is JUST:
0
2
4
6
8
10
...as main() will return immediately after #7 below.
If that is the case, why should the first 5 work? The same example as earlier, no block objects associated.
dispatch_group.notify is an async call. Breaking down what actually happens in your code, this is what's actually happening:
-
You (I did, and I suspect you did as well) are running on the main thread.
-
You create the DispatchGroup.
-
You call dispatch_group.notify, passing a block which will be called on the main thread.
-
dispatch_group.notify notes that the count and schedule your block to fire.
-
You call "dispatch_group.enter" 10 times.
-
Your loop runs 10 times:
- Even numbers call "dispatch_group.leave" and print:
0
2
4
6
8
10
- Odd numbers call DispatchQueue.main.asyncAfter, scheduling a block.
-
Your code block snippet, passing control back to the main thread/calling code.
-
The block filed at #3 runs, printing:
Exited
- The code blocks filed at #6 run, printing:
MainAsync 1 count: 7
MainAsync 3 count: 8
MainAsync 5 count: 9
MainAsync 7 count: 10
MainAsync 9 count: 11
Does that all make sense now?
__
Kevin Elliott
DTS Engineer, CoreOS/Hardware