Joey Carson
Joey Carson

Reputation: 3113

Why doesn't my NSOperationQueue stop executing when suspended?

I have a loop which I run and in each iteration I have a block that I want run on an NSOperationQueue. The underlying queue is serial. This loop could add hundreds of potentially long running block tasks. When I set m_opQueue.suspended = YES the blocks will still keep executing.

I'm well aware that a single block cannot stop right in the middle, but I expected that pausing the NSOperationQueue would simply not execute the next operation until suspended was false.

Can anyone explain whether I'm wrong or how I achieve what I want?

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];

}

Upvotes: 3

Views: 1020

Answers (1)

Rob
Rob

Reputation: 437552

This curious behavior you describe (where previously enqueued operations will continue to start even after the queue has been suspended), is caused by how you created the serial queue.

Generally, you create a serial operation queue by setting maxConcurrentOperationCount:

m_OpQueue.maxConcurrentOperationCount = 1;

If you do that (no need to set underlyingQueue), you see the expected behavior.

Upvotes: 3

Related Questions