PerformSelectorInBackground 和 NSOperation 子类之间的区别

发布于 2024-09-03 14:02:02 字数 570 浏览 0 评论 0原文

我创建了一个用于运行深度计数器循环的测试应用程序。我分别使用 PerformSelectorInBackground 和 NSOperation 子类在后台线程中运行循环函数。

我还使用performSelectorOnMainThread 来通知backgroundthread 方法中的主线程,并使用NSOperation 子类中的[NSNotificationCenter defaultCenter] postNotificationName 来通知主线程更新UI。

最初,两个实现都给了我相同的结果,并且我能够更新 UI 而不会出现任何问题。我发现的唯一区别是两个实现之间的线程数。

PerformSelectorInBackground 实现创建了一个线程,并在循环完成后终止,我的应用程序线程计数再次变为 1。

NSOperation 子类实现创建了两个新线程并在应用程序中保持存在,在 main() 中循环完成后我可以看到 3 个线程功能。

所以,我的问题是为什么 NSOperation 创建了两个线程,为什么它没有像第一个后台线程实现一样被终止?

我有点困惑,无法决定哪种实现在性能和内存管理方面是最好的。

I have created one testing app for running deep counter loop. I run the loop function in background thread using performSelectorInBackground and also NSOperation subclass separately.

I am also using performSelectorOnMainThread to notify main thread within backgroundthread method and [NSNotificationCenter defaultCenter] postNotificationName within NSOperation subclass to notify main thread for updating UI.

Initially both the implementation giving me same result and i am able to update UI without having any problem. The only difference I found is the Thread count between two implementations.

The performSelectorInBackground implementation created one thread and got terminated after loop finished and my app thread count again goes to 1.

The NSOperation subclass implementation created two new threads and keep exists in the application and i can see 3 threads after loop got finished in main() function.

So, my question is why two threads created by NSOperation and why it didn't get terminated just like the first background thread implementation?

I am little bit confuse and unable to decide which implementation is best in-terms of performance and memory management.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲歌长辞 2024-09-10 14:02:02

操作队列很可能使线程保持活动状态,等待新操作的出现。

您必须记住,操作队列旨在高效地处理许多操作,因此为每个操作创建和销毁线程将会损害性能。因此,您所看到的可能只是队列通过保持线程池处于活动状态而设计的工作方式。

基本上,只要您正确使用操作队列并根据文档,我就不会担心。

It's likely the operation queue is keeping threads alive, waiting for new operations to appear.

You have to remember that the operation queue is designed to work efficiently with many operations, so creating and destroying threads for each operation is going to hurt performance. So what you are seeing is probably just the way the queue is designed to work by keeping a pool of threads alive.

Basically, as long as you are using the operation queue properly and according to the documentation I wouldn't worry about it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文