What's the difference between synchronous and asynchronous calls in Objective-C, versus multi-threading?

For the longest time I thought asynchronous was synonymous to running something on a background thread, while synchronous meant on the main thread (blocking UI updates and interactions). I understand that not running on the main thread for expensive actions is because it doesn’t allow UI actions to occur as the main thread is occupied, but why is synchronous troublesome?

However, it’s since came to my attention that you can make asynchronous calls on the main thread, and synchronous calls on background threads.

I always hear people saying not to use expensive calls synchronously or on the main thread, as it will block the UI for the user. Are these two separate issues I should be making sure I don’t do? What are the differences?

You may have a long running task that you need to complete - for instance, to download an image from the web, or maybe to do some complex data manipulation

If the task is performed on a single thread, then nothing else can be done until that task finishes. Touches will be delayed, animations will pause etc. The longer the task is, the more noticeable it will be that the rest of the app is hanging, whilst that operation is being completed.

To fix this, you can perform the expensive operation on a background thread. Your animations and touch handling are handled on the main thread, so they won’t be blocked by the execution of this task. Once the task is complete, you callback to the main thread with the result, and then the background thread finishes.

Some tasks are always expected to take a long time, for instance, making a web call, so they usually offer a sync and async api. The async api is really just a short cut to make a background thread and call the sync api.

Sync: [Do long running task]
Async: [Make Background thread] [Do long running task] [Call back to main thread]

For this reason, the async version will often take a block, that it will call after the task has finished.

So, if you are already on a background thread, you can use the sync version. Perhaps you want to chain many long running tasks? Then you can make a background thread, and use the sync versions.

Most of the time, though, you’re on the main thread, so the easiest thing to do, to save yourself the hassle of managing the threading yourself, is you use the async version.

That’s why you make async calls on the main thread, and sync on background threads. Hope that helps!

1 Like