By design, dispatch_*()
APIs have no notion of cancellation. The reason for this is because it is almost universally true that your code maintains the concept of when to stop or not and, thus, also supporting that in the dispatch_*() APIs would be redundant (and, with redundancy comes errors).
Thus, if you want to "stop early" or otherwise cancel the pending items in a dispatch queue (regardless of how they were enqueued), you do so by sharing some bit of state with the enqueued blocks that allows you to cancel.
if (is_canceled()) return;
Or:
__block BOOL keepGoing = YES;
dispatch_*(someQueue, ^{
if (!keepGoing) return;
if (weAreDoneNow) keepGoing = NO;
}
Note that both enumerateObjectsUsingBlock:
and enumerateObjectsWithOptions:usingBlock:
both support cancellation because that API is in a different role. The call to the enumeration method is synchronous even if the the actual execution of the enumerating blocks may be fully concurrent depending on options.
Thus, setting the *stopFlag=YES
tells the enumeration to stop. It does not, however, guarantee that it will stop immediately in the concurrent case. The enumeration may, in fact, execute a few more already enqueued blocks before stopping.
(One might briefly think that it would be more reasonable to return BOOL
to indicate whether the enumeration should continue. Doing so would have required that the enumerating block be executed synchronously, even in the concurrent case, so that the return value could be checked. This would have been vastly less efficient.)