dispatch_after并不总是有效

时间:2016-10-17 00:45:35

标签: objective-c grand-central-dispatch nsoperation nsoperationqueue dispatch-after

我尝试了以下简单测试,以了解Interaction between qualityOfService property of NSOperationQueue & NSOperation added to it

中的QoS问题

在执行此操作时,我遇到了一个奇怪的问题,其中dispatch_after中的代码并不总是有效。有人可以帮助我理解案例2无效的原因。

在这种情况下,dispatch_after中的取消代码会被执行

  NSBlockOperation *newOp = [NSBlockOperation new];
    __weak NSBlockOperation *weakOp = newOp;
    [newOp addExecutionBlock:^{
        NSBlockOperation *innerOp = weakOp;
        while (![innerOp isCancelled])
        {
            usleep(2000000) ;
            NSLog(@"New Op QOS is %ld",innerOp.qualityOfService);
        }
        NSLog(@"Exiting snce new Op is cancelled");
    }];
    [self.myCustomQ addOperation:newOp];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSBlockOperation *innerOp = weakOp;
        [innerOp cancel];
        NSLog(@"Cancelling block 2");
    });

但在这种情况下,它没有被执行

self.myMainQ = [NSOperationQueue mainQueue];
NSLog(@"QOS of main Q is %ld",self.myMainQ.qualityOfService);

__weak ViewController *weakSelf = self;
self.fromMainOp = [NSBlockOperation blockOperationWithBlock:^{
    ViewController *innerSelf = weakSelf;
    while (![innerSelf.fromMainOp isCancelled])
    {
        usleep(1000000) ;
        NSLog(@"Main OP QOS is %ld",innerSelf.fromMainOp.qualityOfService);
    }
}];
NSLog(@"QOS of main op is %ld",self.fromMainOp.qualityOfService);
[self.myMainQ addOperation:self.fromMainOp];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    ViewController *innerSelf = weakSelf;
    [innerSelf.fromMainOp cancel];
    NSLog(@"Cancelling operation");
});

1 个答案:

答案 0 :(得分:4)

<div id="status-buttons" class="text-center">
  <a href="#/form/regalo" class="active"><span>1</span> Step 1</a>
  <a href="#/form/tusdatos"><span>2</span> Step 2</a>
</div>

该代码看起来非常像阻塞主队列,直到该块退出。如果主队列被阻塞,则不会在主队列上调度任何块。