创建 iOS 云集成框架时,基于块的方法是否应该在主线程上返回?
我正在为 iOS 创建一个云集成框架。我们允许您通过选择器/回调和块实现进行同步和异步保存、查询、计数和删除。正确的做法是什么?在主线程或后台线程上运行完成块?
I am in the middle of creating a cloud integration framework for iOS. We allow you to save, query, count and remove with synchronous and asynchronous with selector/callback and block implementations. What is the correct practice? Running the completion blocks on the main thread or a background thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于简单的情况,我只是参数化它并在辅助线程上完成我能做的所有工作:
默认情况下,将在任何线程上进行回调(这是最有效和直接的 - 通常在操作完成后)。这是默认设置,因为通过 main 进行消息传递的成本可能相当高。
客户端可以可选指定消息必须在主线程上发出。这样,它就需要一行或一个参数。如果安全性比效率更重要,那么您可能需要反转默认值。
您还可以尝试批处理和合并一些消息,或者只是在主运行循环上使用计时器来进行发布。
在您的某些工作中同时考虑连接模型和分离模型。
如果您可以将任务简化为结果(如果不需要,则删除增量更新的功能),那么您可以简单地运行任务,完成工作,并在完成时提供结果(或错误)。
For simple cases, I just parameterize it and do all the work i can on secondary threads:
By default, callbacks will be made on any thread (where it is most efficient and direct - typically once the operation has completed). This is the default because messaging via main can be quite costly.
The client may optionally specify that the message must be made on the main thread. This way, it requires one line or argument. If safety is more important than efficiency, then you may want to invert the default value.
You could also attempt to batch and coalesce some messages, or simply use a timer on the main run loop to vend.
Consider both joined and detached models for some of your work.
If you can reduce the task to a result (remove the capability for incremental updates, if not needed), then you can simply run the task, do the work, and provide the result (or error) when complete.
Apple 的 NSURLConnection 类在启动它的线程上回调其委托方法,同时在后台线程上执行其工作。这似乎是一个明智的程序。框架的用户很可能不会喜欢在编写简单的回调块时担心线程安全性,就像您创建一个新线程来运行它一样。
硬币的两面:如果回调涉及 GUI,则必须在主线程上运行。另一方面,如果它不这样做,并且会做很多工作,那么在主线程上运行它会阻塞 GUI,导致最终用户感到沮丧。
最好将回调放在已知的、有记录的线程上,并让应用程序程序员确定对 GUI 的影响。
Apple's
NSURLConnection
class calls back to its delegate methods on the thread from which it was initiated, while doing its work on a background thread. That seems like a sensible procedure. It's likely that a user of your framework will not enjoy having to worry about thread safety when writing a simple callback block, as they would if you created a new thread to run it on.The two sides of the coin: If the callback touches the GUI, it has to be run on the main thread. On the other hand, if it doesn't, and is going to do a lot of work, running it on the main thread will block the GUI, causing frustration for the end user.
It's probably best to put the callback on a known, documented thread, and let the app programmer make the determination of the effect on the GUI.