5.6. Performing Non-UI Related Tasks Synchronously with GCD
Problem
You want to perform synchronous tasks that do not involve any UI-related code.
Solution
Use the dispatch_sync
function.
Discussion
There are times when you want to perform tasks that have nothing to do with the UI or interact with the UI as well as doing other tasks that take up a lot of time. For instance, you might want to download an image and display it to the user after it is downloaded. The downloading process has absolutely nothing to do with the UI.
For any task that doesn’t involve the UI, you can use global concurrent queues in GCD. These allow either
synchronous or asynchronous execution. But synchronous execution does not
mean your program waits for the code to finish before continuing. It
simply means that the concurrent queue will wait until your task has
finished before it continues to the next block of code on the queue.
When you put a block object on a concurrent queue, your own program
always continues right away without waiting for
the queue to execute the code. This is because concurrent queues, as
their name implies, run their code on threads other than the main
thread. (There is one exception to this: when a task is submitted to a
concurrent or a serial queue using the dispatch_sync function, iOS will, if
possible, run the task on the current thread, which
might be the main thread, depending on where the code path is at the moment. This is an optimization that has been programmed on GCD, as we shall ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access