Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are completion handler closures always running in the background thread?

Completion handler closures are common in iOS development, such as dataTask(with:completionHandler:) in the URLSession class.

The UI engine is managed by the main thread, the API calls by URLSession are run under the background thread and must be dispatched to the main thread if a UI update is needed in the handler.

Question 1: Do all completion handler closures from the iOS framework run in the background thread?

Question 1.1: Do all escaping closures, for example, created by developers, run in the background thread?

Question2: I've seen up to 8 threads in the iPhone X simulator. Which one is the main thread and which one is the background thread in ios? Do they have different priorities and computational power?

like image 705
SLN Avatar asked Aug 24 '18 20:08

SLN


1 Answers

Keep in mind that you are really asking about queues and threading more than completion handlers and closures. Code of any type is executed on a queue (which consists of one or more threads). There is nothing special about completion handler closures in this regard.

Q1 - Most iOS SDK provided completion handlers are called on a background queue but don't make that assumption unless the documentation specifically states what queue it is called on. Even URLSession can be configured to run on a specific queue, including the main queue.

Q1.1 - Closures that you write are run on whatever queue you call them from. There is no magic that makes them run on a background queue.

Q2 - The first thread is always the only thread of the main queue. All other threads are from background queues. Each thread can have whatever priority is was given based on the properties of its queue.

You should review the Dispatch documentation for further details, especially DispatchQueue.

like image 128
rmaddy Avatar answered Oct 22 '22 08:10

rmaddy