杀死或打断dispatch_queue_t方法

Kill or interrupt dispatch_queue_t method

使用这段代码,我可以在后台执行我的代码。

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
        dispatch_async(queue, ^{
            // Perform async operation
            // Call your method/function here
            // Example:
            // NSString *result = [anObject calculateSomething];
            dispatch_sync(dispatch_get_main_queue(), ^{
                // Update UI
                // Example:
                // self.myLabel.text = result;
            });
        });

但我找不到中断此后台线程的解决方案。有什么方法可以杀死或中断队列吗?

您真的应该使用 NSOperationQueue 来管理您的代码流并创建您的 NSOperation 实例以尊重 cancelled 属性。完成此操作后,您可以轻松地挂起队列(以暂停执行未来的操作)并取消任何(或所有)操作。

请注意,您有责任将操作编写为可取消 - 它需要决定在处理过程中的哪些点检查 cancelled 的状态并中止进一步处理是明智的。