我在我的应用中使用以下(简化的)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()
block 会按预期触发,但如果网络调用超时并且 _recommendationDictionary
是零,dispatch_async(dispatch_get_main_queue()
永远不会触发。
如果 NetworkUtility
正在返回一个值,为什么 dispatch_async(dispatch_get_main_queue()
没有立即触发?
最佳答案
block 在主队列中排队。主队列是一个串行队列,它会按顺序执行入队的 block 。
如果您在主线程上使用 CFRunLoop,那么主调度队列会在该运行循环中耗尽,因此如果运行循环被其他事件占用,也会导致执行这些 block 的延迟。
如果您实际上不需要执行在主线程上序列化的 UI 或其他事件,则最好不要使用主队列。
关于ios - dispatch_async(dispatch_get_main_queue()在 NSMutableURLRequest 超时间隔后未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33903471/