Reputation: 1751
I am hoping to learn whether there are any negative implications of running an asynchronous NSURLConnection inside of a dispatch. I am using a dispatch because it seems much cleaner than a timer for my purposes.
The call is asynchronous, but I want to ensure that using dispatch_after will not block the UI. Can someone help me understand if dispatch_after will block the UI/app in any way for those 10 seconds? Thank you!
int delaySeconds = 10;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delaySeconds
* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
aURL = [NSURL URLWithString:@"http://google.com"];
request = [NSMutableURLRequest requestWithURL:aURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[NSURLConnection sendAsynchronousRequest:request queue:
[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response) {
//do something with response
}];
});
P.S. I have taken a look at Does dispatch_after block the main thread? but I'm still a bit confused.
Upvotes: 2
Views: 879
Reputation: 318824
The code inside the dispatch_after
doesn't block anything until it actually runs after the delay. Then it runs on the specified queue.
Since you specify the main queue, the code will be run on the main UI thread. But the UI is not "blocked" during the delay.
But this example is a bad one. While the NSURL
and NSURLRequest
creation are done on the main thread, the actually execution of the request is done asynchronously so the main thread is not being blocked during the request. It is not until the completion handler is called do you get back to the main thread again. But this is because you specific the main queue for the completion block, not because the dispatch_after
is being done on the main thread.
So the only real code being run on the main thread here is the NSURLConnection
completion block. The actual request is done in the background (since it is asynchronous). The other code on the main thread is trivial.
And no thread is being blocked during the delaySeconds
before the dispatched block is run.
Upvotes: 4