美文网首页
GCD使用介绍:队列组dispatch group

GCD使用介绍:队列组dispatch group

作者: 愛我你就抱抱我 | 来源:发表于2017-07-05 16:27 被阅读0次
    在使用GCD进行任务操作时,有时会希望若干个任务执行之间有先后执行的依赖关系,
    例如,当A、B两个异步任务完成后,再去完成C任务,
    这时就可以使用队列组dispatch group来完成。
    
    - (IBAction)startTask:(id)sender {  
        NSLog(@"0--%@", [NSThread currentThread]);
        //创建队列组
        dispatch_group_t group = dispatch_group_create(); 
        //创建并行队列
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    
        //创建队列组中的第一个异步任务
        dispatch_group_async(group, queue, ^{
            NSLog(@"1.1--%@", [NSThread currentThread]);
            //下载网络图片
            NSString *urlStr = @"http://7xta2c.com1.z0.glb.clouddn.com/99logo.png";
            NSURL *url = [NSURL URLWithString:urlStr];
            NSData *imageData = [NSData dataWithContentsOfURL:url];
            UIImage *image = [UIImage imageWithData:imageData];       
            //返回主队列设置图片
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"1.2--%@", [NSThread currentThread]);
                self.task1ImageView.image = image;
            });
        });   
        //创建队列组中的第二个异步任务
        dispatch_group_async(group, queue, ^{
           NSLog(@"2.1--%@", [NSThread currentThread]);
            //下载网络图片
            NSString *urlStr = @"http://7xta2c.com1.z0.glb.clouddn.com/99logo.png";
            NSURL *url = [NSURL URLWithString:urlStr];
            NSData *imageData = [NSData dataWithContentsOfURL:url];
            UIImage *image = [UIImage imageWithData:imageData];        
            //返回主队列设置图片
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"2.2--%@", [NSThread currentThread]);
                self.task2ImageView.image = image;
            });       
        });    
        //任务组中的任务完成后,执行的动作
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"3--%@", [NSThread currentThread]);
           self.taskLabel.text = @"下载完成";
        });  
    }
    

    相关文章

      网友评论

          本文标题:GCD使用介绍:队列组dispatch group

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