最近在项目中有一需求:假设有三个异步请求A、B、C,等这三个异步请求完成之后,通知程序执行D方法,但又不要阻塞线程!貌似面试的时候面试官也喜欢问这种问题,第一反应是用GCD处理,之前也看过一些GCD资料,但是没有实际操作过,今天网上又看了下GCD的资料,找到了简单的解决办法!
用最简单的办法去解决复杂的问题!!!
附以下代码:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
/**创建dispatch组*/
dispatch_group_t group = dispatch_group_create();
for (NSInteger i = 0; i < 10; i++) {
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
/**此处是异步请求*/
[WBRequestManager startGETRequestHost:(NSString *)host urlString:urlString argument:param completionBlock:^(WBResponseModel *model) {
dispatch_group_leave(group);
}];
});
}
/**为group设置通知一个block,当group关联的block执行完毕后,就调用这个block*/
dispatch_group_notify(group, queue, ^{
NSLog(@"It's done!!!");
});
PS: 手动管理group关联的block的运行状态(或计数),进入和退出group次数必须匹配
dispatch_group_enter(group);
dispatch_group_leave(group);
之前看GCD相关内容,将想要执行的代码写入下面block块中:
dispatch_group_async(group, queue, ^{
/**此处写要执行的代码*/
});
说是和调用dispatch_group_enter(group); dispatch_group_leave(group);
等价的,经测试,其实不等价,dispatch_group_async里面只好执行同步的方法,如果是异步的请求,并不会等请求返回结果后再通知dispatch_group_notify进行处理!
信号量处理异步请求
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_group_async(group, queue, ^{
[WBRequestManager startGETRequestHost:(NSString *)host urlString:urlString argument:param completionBlock:^(WBResponseModel *model) {
dispatch_semaphore_signal(semaphore);
}];
});
dispatch_group_async(group, queue, ^{
[WBRequestManager startGETRequestHost:(NSString *)host urlString:urlString argument:param completionBlock:^(WBResponseModel *model) {
dispatch_semaphore_signal(semaphore);
}];
});
dispatch_group_notify(group, queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});