如何停止调度队列

Posted

技术标签:

【中文标题】如何停止调度队列【英文标题】:How can I stop the Dispatch Queue 【发布时间】:2012-11-23 06:36:41 【问题描述】:

我正在使用 Dispatch Queue 加载图像,但如果我不希望它在某个时候加载所有图像,我不知道如何停止队列。

- (void) loadImageInBackgroundArr1:(NSMutableArray *)urlAndTagReference 
    myQueue1 = dispatch_queue_create("com.razeware.imagegrabber.bgqueue", NULL);        
    for (int seriesCount = 0; seriesCount <[seriesIDArr count]; seriesCount++) 
        for (int i = 0; i < [urlAndTagReference count]; i++) 
            dispatch_async(myQueue1, ^(void) 
                NSData *data0 = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[urlAndTagReference objectAtIndex:i]]];
                UIImage *image = [[UIImage alloc]initWithData:data0];
                dispatch_sync(dispatch_get_main_queue(), ^(void) 

                for (UIView * view in [OD_ImagesScrollView subviews]) 

                    if ([view isKindOfClass:[UIView class]]) 

                        for (id btn in [view subviews]) 
                            if ([btn isKindOfClass:[UIButton class]]) 

                                                   UIButton *imagesBtn = (UIButton *)btn;
                        for (UIActivityIndicatorView *view in [imagesBtn subviews]) 
                            if ([view isKindOfClass:[UIActivityIndicatorView class]]) 
                                if (imagesBtn.tag == seriesCount*100+100+i) 
                                    if (view.tag == seriesCount*100+100+i) 
                                        [imagesBtn setImage:image forState:UIControlStateNormal];
                                        [view stopAnimating];
                                        [view removeFromSuperview];
                                        view = nil;
                                        imagesBtn = nil;
                                    
                                
                            
                        
                      
                     
                   
                  

            );

            [image release];
            image = nil;
           [data0 release];
            data0 = nil;
        );

    



【问题讨论】:

【参考方案1】:

调度队列不支持取消。两个明显的选择:

    将您自己的取消标志保留为实例变量,并让块在继续其工作之前检查该标志。所有的块最终都会运行,但是在你设置取消标志之后运行的块会很快返回。

    使用NSOperationQueue 而不是调度队列。 Operation queues support cancelling。如果您在某个操作开始运行之前取消它,则它根本不会运行。如果操作已经在运行,它不会被中断,但你可以让它检查它的isCancelled标志并提前返回。

【讨论】:

以上是关于如何停止调度队列的主要内容,如果未能解决你的问题,请参考以下文章

如何停止现有的调度队列并开始新的?

如何使用 DispatchQueue 从单例字典启动和停止 Firebase 性能跟踪

如何停止音频队列?

视图关闭时如何停止视图模型中的调度计时器?

Laravel如何停止/重新启动特定队列的工作人员?

Jenkins批量停止队列中卡主的jobs