dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self requestA];
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self requestB];
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self requestC];
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//刷新界面
});
- (void)requestA
{
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[Request postWithURL:url params:params success:^(id response){
dispatch_semaphore_signal(sema);
//处理response
} failure:^(NSError *error) {
dispatch_semaphore_signal(sema);
//处理错误
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
requestB和requestC同上。我这就不写了。
//还有一种情况就是,如果最后一个网络请求是依赖前面的所以请求
//这里需要这样改一下
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//刷新界面
});
上面requestA、requestB、requestC加了信号量同时使用GCD多线程的调度组后,他们也是异步执行,执行的先后顺不会卡住主线程。当A、B、Crequest的信号量全部都释放后,就会通知group_notify并执行其操作。
希望我的解决办法能帮助到有这些相关需求的朋友。
作者:Naruto_yuqin
来源:CSDN
原文:https://blog.csdn.net/yq910902/article/details/52528750
版权声明:本文为博主原创文章,转载请附上博文链接!
网友评论