在 NSURLConnection
的异步请求完成处理程序中对主队列使用 dispatch_async()
是否可能导致死锁?
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Alsways perform such code on the main queue/thread
/// At this point I update the UI
});
}
}];
如果是,我该如何解决?
最佳答案
您的代码没有理由死锁。但是可能会有误会
关于 queue
参数。这是完成 block 所在的队列
执行,而不是用于在后台加载数据的队列。
sendAsynchronousRequest
总是在后台队列中加载数据,并且不会阻塞主线程。
因此,要在主线程上执行完成处理程序,您不需要
创建一个操作队列,您可以将代码简化为:
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
// This is executed on the main thread.
// Update UI elements ...
if (error) {
}
}];
关于ios - 异步连接完成处理程序中 dispatch_async 死锁的可能性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21389850/