码迷,mamicode.com
首页 > 其他好文 > 详细

dispatch group使用方法详解

时间:2015-01-31 12:22:35      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

第一、dispatch group可以用来将多个block组成一组以监测这些Block全部完成或者等待全部完成时发出的消息。使用函数dispatch_group_create来创建,然后使用函数dispatch_group_async来将block提交至一个dispatch queue,同时将它们添加至一个组。使用dispatch_group_notify,增加监听,当group内的block全部执行完时,再执行该函数指定的block

dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_group_t group=dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:4];
        NSLog(@"blk0");});
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@"blk1");});
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:3];
        NSLog(@"blk2");});
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{NSLog(@"done");});

    NSLog(@"HELLO");


    执行结果:
2015-01-30 17:18:00.845 testApp[1870:60b] HELLO
2015-01-30 17:18:02.847 testApp[1870:3607] blk1
2015-01-30 17:18:03.848 testApp[1870:3807] blk2
2015-01-30 17:18:04.846 testApp[1870:1903] blk0
2015-01-30 17:18:04.849 testApp[1870:60b] done
第二、dispatch_group_wait(group, DISPATCH_TIME_FOREVER); 
等待group关联的block执行完毕,也可以设置超时参数,如果dispatch_group_wait函数的返回值不为零,说明group内处理为结束,否则为零
dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_group_t group=dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:4];
        NSLog(@"blk0");});
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@"blk1");});
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:3];
        NSLog(@"blk2");});
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{NSLog(@"done");});
    int result=dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC));
    if (result==0) {
        NSLog(@"the group has finished");
    }else{
        NSLog(@"the group is processing");
    }
    NSLog(@"hello");









dispatch group使用方法详解

标签:

原文地址:http://blog.csdn.net/richard_rufeng/article/details/43309407

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!