How do I kill/suspend/close an asyncronous block in GCD?

谁说我不能喝 提交于 2019-11-29 00:44:05

There is no built in way to cancel GCD blocks. They're rather set and forget. One way I've done this in the past is to provide 'tokens' for blocks.

- (NSString*)dispatchCancelable:(dispatch_block_t)block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (!checkIfCanceled)
            block();
    }
    return blah; //Create a UUID or something
}

- (void)cancelBlock:(NSString*)token
{
   //Flag something to mark as canceled
}

That depends on what your GCDHandler is doing. There's some pretty good videos about GCD on the Apple dev site - you might want to move up a layer (into Cocoa) and use NSOperationQueue and NSOperations (either your own subclass or NSBlockOperation). They're all built on top of GCD and the abstraction layer might be more appropriate for what you are trying to do (which you don't state - is it a network request? etc.)

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