performSelectorInBackground和NSOperation Subclass之间的区别(Difference between performSelectorInBackground

编程入门 行业动态 更新时间:2024-10-21 19:35:26
performSelectorInBackground和NSOperation Subclass之间的区别(Difference between performSelectorInBackground and NSOperation Subclass)

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

我也使用performSelectorOnMainThread来通知backthread方法中的主线程和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.

最满意答案

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

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

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

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.

更多推荐

本文发布于:2023-08-07 08:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462318.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   NSOperation   performSelectorInBackground   Difference   Subclass

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!