ios - 异步连接完成处理程序中 dispatch_async 死锁的可能性

标签 ios objective-c cocoa-touch grand-central-dispatch deadlock

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/

相关文章:

ios - 我可以使用iOS 6 UITabBar 的样式吗?

ios - 从 UITabBarController 的 moreNavigationController 中移除 rightBarButtonItem

ios - 如何减慢 CALayer.transform 动画的速度?

ios - 使用动画创建自定义 View

iOS 只存储一点点数据

iphone - UIPickerView pickerView :viewForRow:forComponent:reusingView: does not affect below iOS 5. 0

iphone - 使用缩进级别在 ios 中的 UITableview 中下拉

ios - 数据库中最后插入的行 id 已成功插入但获取该 id 为 0?

iphone - 用于可转换 UILocalNotification 的自定义核心数据访问器

iphone - UIActionSheet 中的奇怪颜色