JPC
JPC

Reputation: 8296

Inspect enqueued GCD blocks?

Let's say I have a serial dispatch queue and I enqueue several operations on it. I've read that I can't cancel operations once they are dispatched. Is it possible to at the very least view what GCD blocks I've dispatched to maybe make a decision if I want to dispatch another one?

Example, I dispatch Operation A to the queue but soon after my application decides to enqueue another Operation A, so now there are 2 of these operations queued up.

Upvotes: 7

Views: 596

Answers (2)

StCredZero
StCredZero

Reputation: 464

Since NSOperation is now built on top of GCD, you can now use addOperationWithBlock: to put your block on an NSOperationQueue, then you can invoke operations on the NSOperationQueue to get an NSArray of unfinished operations.

The problem with this, is that this is more than two operations and is not atomic, so it's entirely possible that your operation will finish in between the time you get the operations array and see if it's contained there.

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html

NSOperations have a prerequisite API, however, so you can enqueue another operation which will only run if your first NSOperation finishes, and use this to keep track of when you should try to enqueue your first NSOperation again.

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html#//apple_ref/doc/uid/TP40004591

Upvotes: 0

Mike Z
Mike Z

Reputation: 4111

As Kevin Ballard said, you need to elaborate on what exactly you are trying to do. One thing you could do is set a flag, like valid_ and then you can effectively cancel all but the current item in the queue by doing something like this:

dispatch_async(queue, ^{
  if (valid_) {
    // perform your task here
  }
});

Then whenever you want to "cancel" the queue, just set your valid_ flag to NO.

Again though, give more info on what you are trying to do and I can give you a better answer.

Upvotes: 2

Related Questions