美文网首页
如何取消GCD任务

如何取消GCD任务

作者: 小白PK大牛 | 来源:发表于2020-03-20 22:01 被阅读0次

    1.dispatch_block_cancel

    iOS8之后可以调用dispatch_block_cancel来取消(需要注意必须用dispatch_block_create创建dispatch_block_t,dispatch_block_cancel也只能取消尚未执行的任务,对正在执行的任务不起作用。)

    - (void)gcdBlockCancel{
        dispatch_queue_t queue = dispatch_queue_create("com.gcdtest.www", DISPATCH_QUEUE_CONCURRENT);
        dispatch_block_t block1 = dispatch_block_create(0, ^{
            sleep(5);
            NSLog(@"block1 %@",[NSThread currentThread]);
        });
        dispatch_block_t block2 = dispatch_block_create(0, ^{
            NSLog(@"block2 %@",[NSThread currentThread]);
        });
        dispatch_block_t block3 = dispatch_block_create(0, ^{
            NSLog(@"block3 %@",[NSThread currentThread]);
        });
        dispatch_async(queue, block1);
        dispatch_async(queue, block2);
        dispatch_block_cancel(block3);
    }
    

    打印结果:

    2018-03-0210:10:30.925com.hua[2796:284866] block2 {number =3, name = (null)}
    2018-03-0210:10:30.930com.hua[2796:284889] block1 {number =4, name = (null)}
    

    2.定义外部变量,用于标记block是否需要取消

    该方法是模拟NSOperation,在执行block前先检查isCancelled = YES ?在block中及时的检测标记变量,当发现需要取消时,终止后续操作。

    - (void)gcdCancel{
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
        __block BOOL isCancel = NO;
        dispatch_async(queue, ^{
            NSLog(@"任务001 %@",[NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"任务002 %@",[NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"任务003 %@",[NSThread currentThread]);
            isCancel = YES;
        });
        dispatch_async(queue, ^{
            // 模拟:线程等待3秒,确保任务003完成 isCancel=YESsleep(3);
            if(isCancel){
                NSLog(@"任务004已被取消 %@",[NSThread currentThread]);
            }else{
                NSLog(@"任务004 %@",[NSThread currentThread]);
            }
        });
    }
    

    打印结果:

    2018-03-0210:15:20.825com.hua[3022:333990] 任务002 {number =4, name = (null)}
    2018-03-0210:10:20.826com.hua[3022:333989] 任务001 {number =3, name = (null)}
    2018-03-0210:10:20.827com.hua[3022:333992] 任务003 {number =5, name = (null)}
    2018-03-0210:10:20.828com.hua[3022:334006] 任务004已被取消 {number =6, name = (null)}
    

    相关文章

      网友评论

          本文标题:如何取消GCD任务

          本文链接:https://www.haomeiwen.com/subject/vtnsyhtx.html