dispatch_async块未被调用

时间:2012-12-03 11:28:59

标签: iphone block dispatch-async

MySynchManager 类正在使用共享实例。

MySynchManager类中的一个函数是

- (void)uploadSession:(NSString *)sessionId {
    // run the upload process on a separate thread to not to block the main thread for user interaction
    // process upload data in serial Queue
    NSLog(@"Inside uploadSession");
    if (!_serialQueue) {
        NSLog(@"uploadSession, _serialQueue is NOT ACTIVE");

        [self setRunLoopStarted:FALSE];
        _serialQueue = dispatch_queue_create("sessionUploadQueue", NULL);

        dispatch_async(_serialQueue, ^{
            [[MySyncManager sharedInstance] dispatchSession:sessionId];
        });
    }
    else {
        //[self setRunLoopStarted:FALSE];
        dispatch_async(_serialQueue, ^{
            [self dispatchSession:sessionId];
        });
        NSLog(@"Adding block to the dispatch queue is complete");
    }
}
从视图控制器调用

uploadSession:@"session"

我遇到的问题有时会调用dispatchSession中的代码,但有时会调用block。 打印块后,我只观察日志打印语句。

你们中任何一个人都可以解释这背后的原因吗?

1 个答案:

答案 0 :(得分:1)

这是奇怪的代码。试试这个

-(void)uploadSession:(NSString *)sessionId
 {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       _serialQueue = dispatch_queue_create("sessionUploadQueue", NULL);
    });

    dispatch_async(_serialQueue, ^{
      [self dispatchSession:sessionId];
    });

 }