标签:dispatch_group 嵌套 异步 并行任务
场景1:
从数据源读到N个值,然后需要遍历这N个值,分别发起http请求。处理完成之后,调用一个最终汇总的方法
这个场景如果用js的async框架,很容易就能实现:
async.series([task1, task2, task3], function(err){ // 汇总代码 }); function task1(callback){ // http请求 callback(null); } function task2(callback){ // http请求 callback(null); } function task3(callback){ // http请求 callback(null); }
dispatch_group_t group = dispatch_group_create(); while([rs next]){ dispatch_group_enter(group); [syncService refreshMembersWithEnterpriseId:enterpriseId LatestSyncTime:latestSyncDate Block:^(BOOL flag){ dispatch_group_leave(group); }]; } dispatch_group_notify(group, dispatch_get_main_queue(), ^{ // 汇总代码 });
后来需求变化了,场景更复杂了点。针对每个值,都要发起多个http请求(场景1只需要请求1次)。所有请求都结束以后,再调用汇总方法
所以一开始我写成类似这样:
dispatch_group_t group = dispatch_group_create(); while([rs next]){ dispatch_group_enter(group); dispatch_group_t group_inner = dispatch_group_create(); dispatch_group_enter(group_inner); [syncService refreshMembersWithEnterpriseId:enterpriseId LatestSyncTime:latestSyncDate Block:^(BOOL flag){ dispatch_group_leave(group_inner); }]; dispatch_group_enter(group_inner); [syncService refreshReportsWithEnterpriseId:enterpriseId LatestSyncTime:latestSyncDate Block:^(BOOL flag){ dispatch_group_leave(group_inner); }]; dispatch_group_notify(group_inner, dispatch_get_global_queue(0, 0), ^{ dispatch_group_leave(group); }); } dispatch_group_notify(group, dispatch_get_main_queue(), ^{ // 汇总代码 });
dispatch_group_t group = dispatch_group_create(); while([rs next]){ dispatch_group_enter(group); [syncService refreshMembersWithEnterpriseId:enterpriseId LatestSyncTime:contactLatestSync Block:^(BOOL flag){ dispatch_group_leave(group); }]; dispatch_group_enter(group); [syncService refreshReportsWithEnterpriseId:enterpriseId LatestSyncTime:reportLatestSync Block:^(BOOL flag){ dispatch_group_leave(group); }]; } dispatch_group_notify(group, dispatch_get_main_queue(), ^{ // 汇总代码 });
标签:dispatch_group 嵌套 异步 并行任务
原文地址:http://blog.csdn.net/kyfxbl/article/details/34861069