NSOperations及其完成块是否同时运行? [英] Do NSOperations and their completionBlocks run concurrently?
问题描述
我在 NSOperationQueue
中添加了一堆 NSOperations
。操作队列将 maxConcurrentOperationCount
设置为1,以便 NSOperations
一个接一个地运行。
I've got a bunch of NSOperations
added to a NSOperationQueue
. The operation queue has the maxConcurrentOperationCount
set to 1, so that the NSOperations
run one after the other.
现在,在 NSOperation
的 completionBlock
中,我想取消所有通过在 NSOperationQueue
上调用 cancelAllOperations
来挂起 NSOperations
。
Now, in the completionBlock
of a NSOperation
I want to cancel all pending NSOperations
by calling cancelAllOperations
on the NSOperationQueue
.
这样做安全吗?我可以确定只有在上一个操作的 completionBlock
具有后,才能调用下一个操作的 start
方法被完全执行?还是上一个操作的 completionBlock
和当前操作的任务同时运行?
Is it safe to do this? Can I be sure that the start
-method of the next operation is called only after the completionBlock
of the previous operation has been fully executed? Or do the completionBlock
of the previous operation and the task of the current operation run concurrently?
我为什么问:我使用AFNetworking执行一批 AFHTTPRequestOperations
,并且仅在该批次的所有先前请求均成功时才要执行一个请求。
The reason why I'm asking: I use AFNetworking to execute a batch of AFHTTPRequestOperations
and want to perform one request only if all previous requests of the batch were successful.
推荐答案
我在下面的发现似乎不再是事实。我已在iOS 8和iOS 9上重新运行测试,并且操作的完成部分始终与下一个操作同时运行。目前,我看不到要等待上一个完成块完成的操作的方法。
My findings below no longer seem to be true. I've re-run the tests on iOS 8 and iOS 9 and the completion block of an operation always runs concurrently with the next operation. Currently, I don't see a way to make an operation wait for the previous completion block to finish.
我只是在一个示例项目中尝试了这种情况。结果如下:
I just tried this scenario in a sample project. Here is the result:
如果 NSOperationQueue
的 maxConcurrentOperationCount
设置为1,一个 NSOperation
的 completionBlock
和下一个 NSOperation
在队列中同时运行。
If the NSOperationQueue
's maxConcurrentOperationCount
is set to 1, an NSOperation
's completionBlock
and the next NSOperation
in the queue run simultaneously.
但是,如果每个 NSOperation
通过调用 addDependency:
,操作的执行要等到前一个操作的 completionBlock
完成。
But, if every NSOperation
is linked to its previous operation by calling addDependency:
, the execution of an operation waits until the previous operation's completionBlock
has finished.
,如果要在当前操作的 completionBlock
中取消下一个操作,并确保在开始操作之前取消了该操作,则必须在 NSOperations
通过调用 addDependency:
So, if you want to cancel the next operation in the completionBlock
of the current operation and be sure that it is cancelled before it is started, you have to set dependencies between the NSOperations
by calling addDependency:
这篇关于NSOperations及其完成块是否同时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!