很多教程告诉你
group如果想在dispatch_queue中所有的任务执行完成后在做某种操作,在串行队列中,可以把该操作放到最后一个任务执行完成后继续,但是在并行队列中怎么做呢。这就有dispatch_group 成组操作。比如:
dispatch_queue_t dispatchQueue = dispatch_queue_create("ted.queue.next", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
NSLog(@"dispatch-1");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
NSLog(@"dspatch-2");
});
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"end");
});
但是当你在每个group里面执行发起异步任务,group并不会等待网络的异步加载完成才出group
所以应该这样写
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_enter(dispatchGroup);
[[NetworkRequestTool sharedNetworkRequestTool]POST:URL_GETAREAID parameters:@{@"areaName": self.flayModel.info.from_city} responseDtoClassType:nil success:^(id responseObject) {
DLLog(@"%@",responseObject)
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
}];
dispatch_group_enter(dispatchGroup);
[[NetworkRequestTool sharedNetworkRequestTool]POST:URL_GETAREAID parameters:@{@"areaName": self.flayModel.info.to_city} responseDtoClassType:nil success:^(id responseObject) {
DLLog(@"%@",responseObject)
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
}];
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"end");
});
这样就会在发起第一个网络请求之后 ,接着发起第二个网络请求,都完成之后通知group完成所有网络请求。
举个栗子
1、初始化一个dispatch_group
dispatch_group_t serviceGroup = dispatch_group_create();
2、向group中添加任务
dispatch_group_async(serviceGroup, queue, ^{
//some work here
}
}
向dispatch中添加你的代码块,然后这些代码块会运行在你指定的queue中。
第二种方法是告诉dispatch group你要开始某个任务了。完成之后你也需要手动退出dispatch group。
dispatch_group_enter(), dispatch_group_leave()两个方法可以实现进入和退出。
3、dispatch完成方式
第一种是阻塞当前的线程,直到dispatch group中所有的任务完成后才会返回
dispatch_group_wait(serviceGroup, DISPATCH_TIME_FOREVER);
第二种不会阻塞当前线程,马上返回
dispatch_group_notify(serviceGroup, dispatch_get_main_queue(), ^{
//won't get here until everything has finished
})
实战场景:
1、从数据源读到N个值,然后要遍历N个值,分别发起http请求。处理完成之后,调用一个最终的
汇总方法。
dispatch_group_t group = dispatch_group_create();
while ([rs next]){
dispatch_group_enter(group);
//网络请求
[syncService sendRequest:request withBlock:^{
dispatch_group_leave(group);
}
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//汇总代码
});
场景2:针对每个值,都要发起多个http请求(上面的场景只需要请求1次)。所有请求都结束之后,再调用汇总方法
dispatch_group_t group = dispatch_group_create();
while([rs next])
{
dispatch_group_enter(group);
[syncService sendRequest:request1 withBlock:^{
//handle result1
dispatch_group_leave(group);
}
dispatch_group_enter(group);
[syncService sendRequest:request2 withBlock:^{
//handle result2
dispatch_group_leave(group);
}
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//汇总代码
} ```