首页 > 代码库 > ios嵌套的异步并行任务场景

ios嵌套的异步并行任务场景

场景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);
}

但是在ios里,就比较麻烦,最后是用dispatch_group实现的:

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(), ^{
    // 汇总代码
});

场景2:

后来需求变化了,场景更复杂了点。针对每个值,都要发起多个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(), ^{
    // 汇总代码
});

写完之后发现,其实在这个场景下,不需要嵌套group,共用一个group也没问题

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(), ^{
    // 汇总代码
});

因为这里并不需要针对每个组做汇总处理,如果每个组还有自己的汇总逻辑需要执行的话,就需要嵌套group了