Cancel GCD block working in thread

旧街凉风 提交于 2020-01-06 04:51:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!