dispatch_async(dispatch_get_main_queue() 在 NSMutableURLRequest 超时间隔后未触发

dispatch_async(dispatch_get_main_queue() not firing after NSMutableURLRequest with timeoutInterval

我在我的应用程序中使用以下(简化的)GCD 调用:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSString *query = "/api/something";
    NSString *parameters = "a=1234&b=5678";   

    _myDict = (NSMutableDictionary*)[NetworkUtility postDataToServer:query withParameters:parameters];  


        // Done with API Call
        dispatch_async(dispatch_get_main_queue(), ^{

            // Do something

        });

});

当调用 NetworkUtility 时,NSURL 连接被调用到:

 NSData *postData = [parameters dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
 NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];

 NSString *urlString = [NSString stringWithFormat:@"https://myapp.com%@", query];

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:7.0];

 [request setHTTPMethod:@"POST"];
 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
 [request setHTTPBody:postData];

 NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

 return response;

结果是,如果网络收到响应,dispatch_async(dispatch_get_main_queue() 块会按预期触发,但如果网络调用超时并且 _recommendationDictionary 为 nil,dispatch_async(dispatch_get_main_queue()从不开火。

如果 NetworkUtility 正在返回值,为什么 dispatch_async(dispatch_get_main_queue() 不立即触发?

块在主队列中排队。主队列是一个串行队列,它会按顺序执行入队的块。

如果您在主线程上使用 CFRunLoop,那么主调度队列会在该 运行 循环中耗尽,因此如果 运行 循环被其他 activity 占用,它还会导致执行这些块的延迟。

如果您实际上不需要执行 UI 或其他在主线程上序列化的活动,您最好不要使用主队列。