完成处理程序关闭是否总是在后台线程中运行? [英] Are completion handler closures always running in the background thread?

查看:63
本文介绍了完成处理程序关闭是否总是在后台线程中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完成处理程序闭包在iOS开发中很常见,例如 URLSession 类中的dataTask(with:completionHandler:).

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

UI引擎由主线程管理,URLSession的API调用在后台线程下运行,如果处理程序中需要UI更新,则必须将其分派到主线程.

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.

问题1 : iOS框架中的所有完成处理程序关闭操作是否都在后台线程中运行?

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

问题1.1 : 例如,由开发人员创建的所有转义闭包都在后台线程中运行吗?

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

问题2 : 我已经在iPhone X模拟器中看到多达8个线程. ios中的哪一个是主线程,哪一个是后台线程?它们具有不同的优先级和计算能力吗?

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?

推荐答案

请记住,与完成处理程序和闭包相比,您真正询问的是队列和线程.任何类型的代码都在队列(由一个或多个线程组成)上执行.在这方面,完成处理程序关闭没有什么特别的.

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-大多数iOS SDK提供的完成处理程序是在后台队列上调用的,但是除非文档中特别说明要在哪个队列上调用,否则不要做此假设.甚至URLSession都可以配置为在特定队列(包括主队列)上运行.

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-您编写的闭包可以在调用它们的任何队列上运行.没有任何魔法可以使它们在后台队列上运行.

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-第一个线程始终是主队列中的唯一线程.所有其他线程均来自后台队列.每个线程可以根据其队列的属性赋予其优先级.

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.

您应该查看调度文档以了解更多详细信息,尤其是DispatchQueue.

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

这篇关于完成处理程序关闭是否总是在后台线程中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆