performSelectorInBackground和NSOperation子类之间的区别 [英] Difference between performSelectorInBackground and NSOperation Subclass

查看:121
本文介绍了performSelectorInBackground和NSOperation子类之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我也使用performSelectorOnMainThread来通知主线程在backgroundthread方法和[NSNotificationCenter defaultCenter] postNotificationName在NSOperation子类内通知主线程更新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.

这篇关于performSelectorInBackground和NSOperation子类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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