GCD组任务三部曲,
- 创建组
- 创建队列(一般选择自定义串行、并行、或者全局)
- 开启任务组任务
- 监听notify回调,处理后续逻辑
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("queueByZxh", DISPATCH_QUEUE_SERIAL);
dispatch_group_async(group, queue, ^{
[NetWorkTool requestWithType:HttpRequestTypePost withHttpHeaderFieldDict:HYUSERTOKEN withUrlString:url withParaments:params withSuccessBlock:^(NSDictionary *responseObject) {
NSLog(@"1111");
} withFailureBlock:^(NSString *errorMsg) {
} progress:^(float progress) {
}];
});
dispatch_group_async(group, queue, ^{
[Advertisement getAdsListByModelType:ModelType_ZHI_BO withResultBlock:^(NSDictionary *adverisementDict) {
NSLog(@"2222");
}];
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"3333");
});
//实际输出是3333、1111/2222、2222/1111
//理想状态输出是 1111 、 2222、 3333,可并不是。 3333先输出了,因为AFN网络请求又开启了新的异步线程,所以要增加信号量控制
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("queueByZxh", DISPATCH_QUEUE_SERIAL);
dispatch_group_async(group, queue, ^{
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[NetWorkTool requestWithType:HttpRequestTypePost withHttpHeaderFieldDict:HYUSERTOKEN withUrlString:url withParaments:params withSuccessBlock:^(NSDictionary *responseObject) {
NSLog(@"1111");
dispatch_semaphore_signal(sem);
} withFailureBlock:^(NSString *errorMsg) {
dispatch_semaphore_signal(sem);
} progress:^(float progress) {
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
});
dispatch_group_async(group, queue, ^{
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[Advertisement getAdsListByModelType:ModelType_ZHI_BO withResultBlock:^(NSDictionary *adverisementDict) {
NSLog(@"2222");
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"3333");
});
//实际输出 最后执行的3333
网友评论