NSOperation对大中央调度 [英] NSOperation vs Grand Central Dispatch
问题描述
我正在学习iOS的并发编程。到目前为止,我已阅读了有关 NSOperation
/ NSOperationQueue
和 GCD
。 使用 NSOperationQueue
超过 GCD
的原因是什么?反之亦然?
听起来像 GCD
和 NSOperationQueue
抽象显式创建 NSThreads
。但是,这两种方法之间的关系对我来说不清楚,所以任何反馈意见赞赏!
GCD
是一个低级的基于C的API,可以非常简单地使用基于任务的并发模型。 NSOperation
和 NSOperationQueue
是做类似事情的Objective-C类。 首先引入了NSOperation
,但从10.6和iOS 4开始, NSOperationQueue
和朋友在内部使用 GCD
。
一般来说,您应该使用最符合您需求的抽象层次。这意味着你通常应该使用 NSOperationQueue
而不是 GCD
,除非你需要做一些 NSOperationQueue
不支持。
请注意, NSOperationQueue
翻译版本的GCD;事实上,你可以使用 NSOperationQueue
非常简单地做很多事情,这需要使用纯粹的 GCD
。 (例如:带宽约束的队列,一次只运行N个操作;建立操作之间的依赖性。 NSOperation
很难用 GCD
。)Apple使用GCD创建了一个非常漂亮的对象友好的API,通过 NSOperation
做了辛苦的工作。除非你有理由不要。
注意:
另一方面,如果你真的需要发送一个块,并且不需要任何 NSOperationQueue
提供的附加功能,使用GCD没有什么问题。只要确定这是工作的正确工具。
I'm learning about concurrent programming for iOS. So far I've read about NSOperation
/NSOperationQueue
and GCD
. What are the reasons for using NSOperationQueue
over GCD
and vice versa?
Sounds like both GCD
and NSOperationQueue
abstract away the explicit creation of NSThreads
from the user. However the relationship between the two approaches isn't clear to me so any feedback to appreciated!
GCD
is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation
and NSOperationQueue
are Objective-C classes that do a similar thing. NSOperation
was introduced first, but as of 10.6 and iOS 4, NSOperationQueue
and friends are internally implemented using GCD
.
In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue
instead of GCD
, unless you need to do something that NSOperationQueue
doesn't support.
Note that NSOperationQueue
isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue
that take a lot of work with pure GCD
. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation
, very difficult with GCD
.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation
. Take advantage of their work unless you have a reason not to.
Caveat:
On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue
provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.
这篇关于NSOperation对大中央调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!