Re: dispatch_async question


Fritz Anderson
 

On Jul 19, 2017, at 8:30 AM, Dave <dave@...> wrote:

In the following code, does it *need* to use the dispatch_async function?

dispatch_async(dispatch_get_main_queue(), ^{
if ([[self delegate] respondsToSelector:@selector(gameCenterManager:availabilityChanged:)])
[[self delegate] gameCenterManager:self availabilityChanged:successDictionary];
});

It sometimes uses it and sometimes it calls the delegate inline. I’m wondering why?

As far as I am aware, the only thing using dispatch_async does, is call the delegate sometime after the current method as returned, which I can’t see is of any benefit and makes things much hard to understand.
It's hard to understand because concurrency is the most difficult task in software engineering. (A debate on "hardest task" might be fun. Please let's not.) If the code you're looking at was thoughtfully-written, the decision to dispatch or not was deliberate.

UI work must be done on the main thread, one operation at a time — in other words, serially, which is easier if you have a queue manager to make sure everything happens in turn. Letting multiple threads interrupt each other as they force a label to change its layout will end badly.

The original code assumes the delegate may require the main thread.

## Assume the caller is **guaranteed** to be on the main thread

The assumption is not to be made lightly. If it's true, this is easy. Call directly. There may be further issues (do not monopolize the UI thread) but those are beyond the scope of your question.

## Assume the caller might not be on the main thread

The work has to be done on the main thread (so the original code assumes). You must use GCD to hand it over to the main dispatch queue. The main queue makes sure the work gets its turn with no interference.

That answers the literal question of why the code is sometimes dispatched, sometimes not. The decisions and the design that drove them (such as why "do it later" may also be the right strategy) are much harder. You can learn, but not in a single email.

— F

Join cocoa@apple-dev.groups.io to automatically receive all group messages.