Learning NSBlockOperation

前端 未结 3 1557
滥情空心
滥情空心 2021-01-30 18:05

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 ex

相关标签:
3条回答
  • 2021-01-30 18:50

    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";
        });
    
    });
    
    0 讨论(0)
  • 2021-01-30 18:50

    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.

    0 讨论(0)
  • 2021-01-30 18:55

    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 :)

    0 讨论(0)
提交回复
热议问题