问题
I have the following block which performs a request in the background.
How may I cancel this request before it has completed?
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *thumbnailData = [NSURLConnection sendSynchronousRequest:request];
...
});
回答1:
You can't. You have to use the asynchronous interface of NSURLConnection
to be able to cancel requests.
回答2:
You can't cancel once you've dispatched...
You can use a workaround, like:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
__block BOOL isCanceled = NO;
dispatch_async(queue, ^{
if (isCanceled)
return;
NSData *thumbnailData = [NSURLConnection sendSynchronousRequest:request];
...
});
回答3:
You can use the higher level "NSOperationQueue", after adding the operation to queue, then you can cancelAllOperations.
来源:https://stackoverflow.com/questions/6090406/cancel-gcd-block-working-in-thread