Learning NSBlockOperation

2019-03-08 08:43发布

问题:

I'm a big fan of blocks, but have not used them for concurrency. After some googling, I pieced together this idea to hide everything I learned in one place. The goal is to execute a block in the background, and when it's finished, execute another block (like UIView animation)...

- (NSOperation *)executeBlock:(void (^)(void))block completion:(void (^)(BOOL finished))completion {

    NSOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:block];

    NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
        completion(blockOperation.isFinished);
    }];

    [completionOperation addDependency:blockOperation];
    [[NSOperationQueue mainQueue] addOperation:completionOperation];    

    NSOperationQueue *backgroundOperationQueue = [[NSOperationQueue alloc] init];
    [backgroundOperationQueue addOperation:blockOperation];

    return blockOperation;
}

- (void)testIt {

    NSMutableString *string = [NSMutableString stringWithString:@"tea"];
    NSString *otherString = @"for";

    NSOperation *operation = [self executeBlock:^{
        NSString *yetAnother = @"two";
        [string appendFormat:@" %@ %@", otherString, yetAnother];
    } completion:^(BOOL finished) {
        // this logs "tea for two"
        NSLog(@"%@", string);
    }];

    NSLog(@"keep this operation so we can cancel it: %@", operation);
}

My questions are:

  1. It works when I run it, but am I missing anything ... hidden land mine? I haven't tested cancellation (because I haven't invented a long operation), but does that look like it will work?
  2. I'm concerned that I need to qualify my declaration of backgroundOperation so that I can refer to it in the completion block. The compiler doesn't complain, but is there a retain cycle lurking there?
  3. If the "string" were an ivar, what would happen if I key-value observed it while the block was running? Or setup a timer on the main thread and periodically logged it? Would I be able to see progress? Would I declare it atomic?
  4. If this works as I expect, then it seems like a good way to hide all the details and get concurrency. Why didn't Apple write this for me? Am I missing something important?

Thanks.

回答1:

I am not an expert in NSOperation or NSOperationQueues but I think below code is a bit better although I think it has some caveats still. Probably enough for some purposes but is not a general solution for concurrency:

- (NSOperation *)executeBlock:(void (^)(void))block
                      inQueue:(NSOperationQueue *)queue
                   completion:(void (^)(BOOL finished))completion
{
    NSOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:block];
    NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
        completion(blockOperation.isFinished);
    }];
    [completionOperation addDependency:blockOperation];

    [[NSOperationQueue currentQueue] addOperation:completionOperation];
    [queue addOperation:blockOperation];
    return blockOperation;
}

Now lets use it:

- (void)tryIt
{
    // Create and configure the queue to enqueue your operations
    backgroundOperationQueue = [[NSOperationQueue alloc] init];

    // Prepare needed data to use in the operation
    NSMutableString *string = [NSMutableString stringWithString:@"tea"];
    NSString *otherString = @"for";

    // Create and enqueue an operation using the previous method
    NSOperation *operation = [self executeBlock:^{
        NSString *yetAnother = @"two";
        [string appendFormat:@" %@ %@", otherString, yetAnother];
    }
    inQueue:backgroundOperationQueue 
    completion:^(BOOL finished) {
        // this logs "tea for two"
        NSLog(@"%@", string);
    }];

    // Keep the operation for later uses
    // Later uses include cancellation ...
    [operation cancel]; 
}

Some answers to your questions:

  1. Cancelation. Usually you subclass NSOperation so you can check self.isCancelled and return earlier. See this thread, it is a good example. In current example you cannot check if the operation has being cancelled from the block you are supplying to make an NSBlockOperation because at that time there is no such an operation yet. Cancelling NSBlockOperations while the block is being invoked is apparently possible but cumbersome. NSBlockOperations are for specific easy cases. If you need cancellation you are better subclassing NSOperation :)

  2. I don't see a problem here. Although note two things. a)I changed the method do to run the completion block in current queue b)a queue is required as a parameter. As @Mike Weller said, you should better supply background queue so you don't need to create one per each operation and can choose what queue to use to run your stuff :)

  3. I think yes, you should make string atomic. One thing you should not forget is that if you supply several operations to the queue they might not run in that order (necessarily) so you could end up with a very strange message in your string. If you need to run one operation at a time serially you can do: [backgroundOperation setMaxConcurrentOperationCount:1]; before start enqueuing your operations. There is a reading-worthy note in the docs though:

    Additional Operation Queue Behaviors An operation queue executes its queued operation objects based on their priority and readiness. If all of the queued operation objects have the same priority and are ready to execute when they are put in the queue—that is, their isReady method returns YES—they are executed in the order in which they were submitted to the queue. For a queue whose maximum number of concurrent operations is set to 1, this equates to a serial queue. However, you should never rely on the serial execution of operation objects. Changes in the readiness of an operation can change the resulting execution order.

  4. I think after reading these lines you know :)



回答2:

You should not be creating a new NSOperationQueue for each executeBlock:completion: call. This is expensive and the user of this API has no control over how many operations can execute at a time.

If you are returning NSOperation instances then you should leave it up to the caller to decide which queue to add them to. But at that point, your method really isn't doing anything helpful and the caller might as well create the NSBlockOperation themselves.

If you just want a simple and easy way to spin off a block in the background and perform some code when it finishes, you're probably better off making some simple GCD calls with the dispatch_* functions. For example:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // do your background work
    // ...

    // now execute the 'completion' code.
    // you often want to dispatch back to the main thread to update the UI
    // For example:

    dispatch_async(dispatch_get_main_queue(), ^{
        // update UI, etc.
        myLabel.text = @"Finished";
    });

});


回答3:

There's no need to set up a block to be run on completion and add dependencies like this. NSBlockOperation like all NSOperation subclasses already has a completionBlock property which will automatically run when the block has finished its work:

@property(copy) void (^completionBlock)(void);

The completion block is run when its block moves to the finished state.