为什么我的 NSOperationQueue 在暂停时不停止执行?

Why doesn't my NSOperationQueue stop executing when suspended?

我有一个循环 运行 并且在每个 迭代中 我有一个我想要 运行 在 NSOperationQueue 上的块。底层队列是串行的。这个循环可以添加数百个可能很长的 运行ning 块任务。当我设置 m_opQueue.suspended = YES 时,块仍将继续执行。

我很清楚单个块不能在中间停止,但我预计暂停 NSOperationQueue 将不会执行下一个操作,直到暂停为 false。

任何人都可以解释我是否错了或者我如何实现我想要的?

dispatch_queue_t index_queue = dispatch_queue_create("someQueue", DISPATCH_QUEUE_SERIAL);
m_OpQueue = [[NSOperationQueue alloc] init];
m_OpQueue.underlyingQueue = index_queue;


for ( NSUInteger i = 0; i < total; i++ ) {

    void (^block)(void) = ^void() {            
        // Do stuff.
        NSLog(@"processing complete.");

    };

    // Effectively adds a NSBlockOperation.
    [m_OpQueue addOperationWithBlock:block];

}

您描述的这种奇怪行为(即使队列已挂起,之前入队的操作仍将继续启动)是由您创建串行队列的方式引起的。

通常,您通过设置maxConcurrentOperationCount:

来创建串行操作队列
m_OpQueue.maxConcurrentOperationCount = 1;

如果您这样做(无需设置 underlyingQueue),您会看到预期的行为。