Question

Is it possible that using dispatch_async() to the main queue inside an NSURLConnection's asynchronous request completion handler can cause a deadlock?

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
             });

         }
     }];

If yes, how can I solve it?

Was it helpful?

Solution

There is no reason why your code should dead-lock. But there might be a misunderstanding about the queue parameter. That is the queue on which the completion block is executed, not the queue that is used for loading the data in the background.

sendAsynchronousRequest does always load the data on a background queue and does not block the main thread. Therefore, to execute the completion handler on the main thread, you don't need to create a operation queue, and you can simplify your code to:

[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) {

     }
 }];

OTHER TIPS

You can't have a deadlock with dispatch_async. It doesn't block the calling queue.

It looks like you're trying to run the NSURLConnection off the main queue and then update the UI on the main queue. This is a good idea. But you get all that for free with the method. The queue parameter says where the completion block should be dispatched...

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (!error) {
        // this will run on the main queue because of the queue param
        // update the ui
    }
}];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top