多任务按照顺序执行时(task1-->task2-->task3-->TaskSuccess)我们通常会用dispatch_group_async、dispatch_group_notify结合来完成或者使用栅栏,但这种操作只针对内部执行的任务是同步的
- dispatch_group_async、dispatch_group_notify结合的方式
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
NSLog(@"task1");
});
dispatch_group_async(group, queue, ^{
NSLog(@"task2");
});
dispatch_group_async(group, queue, ^{
NSLog(@"task3");
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"TaskSuccess");
});
- 栅栏方式
dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(queue, ^{
NSLog(@"task1");
});
dispatch_async(queue, ^{
NSLog(@"task2");
});
dispatch_async(queue, ^{
NSLog(@"task3");
});
dispatch_barrier_async(queue, ^{
NSLog(@"TaskSuccess");
});
对于任务中有异步的,可以使用采用dispatch_group_enter、dispatch_group_leave或者信号量实现
- dispatch_group_enter、dispatch_group_leave结合的方式
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[self loadData1:^{
NSLog(@"task1");
dispatch_group_leave(group);
}];
dispatch_group_enter(group);
[self loadData2:^{
NSLog(@"task2");
dispatch_group_leave(group);
}];
dispatch_group_wait(group, DISPATCH_TIME_NOW);// task1 task2 执行完 下面才会执行
dispatch_group_enter(group);
[self loadData3:^{
NSLog(@"task3");
dispatch_group_leave(group);
}];
// 1 2 3 都完成 才会执行
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"taskSuccess!");
});
//调用方法
-(void)loadData1:(nullable void (^)(void))block{
NSDictionary *parDic = @{};
[NetWorkRequest postNetRequestData:StaffRuleUrl parmeters:parDic response:^(NSDictionary *response) {
if (response) {
if ([response[@"stat"] isEqualToString:@"0"]) {
block();
}
}
} netError:^(NSError *error) {
}];
}
-(void)loadData2:(nullable void (^)(void))block{
NSDictionary *parDic = @{};
[NetWorkRequest postNetRequestData:StaffRuleUrl parmeters:parDic response:^(NSDictionary *response) {
if (response) {
if ([response[@"stat"] isEqualToString:@"0"]) {
block();
}
}
} netError:^(NSError *error) {
}];
}
-(void)loadData3:(nullable void (^)(void))block{
NSDictionary *parDic = @{};
[NetWorkRequest postNetRequestData:StaffRuleUrl parmeters:parDic response:^(NSDictionary *response) {
if (response) {
if ([response[@"stat"] isEqualToString:@"0"]) {
block();
}
}
} netError:^(NSError *error) {
}];
}
先执行到dispatch_group_wait,然后才去执行上边的两个任务,由于enter数不等于leave数,进行等待,当task1、task2完成后调用dispatch_group_leave ,enter数等于leave数,才去执行请求3。 task1、task2、task3都执行后,dispatch_group_notify最后执行
- 信号量方式
dispatch_async(dispatch_get_global_queue(0, 0), ^{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self loadData1:^{
NSLog(@"task1");
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self loadData2:^{
NSLog(@"task2");
}];
});
执行到dispatch_semaphore_wait时,由于信号量为0,进行等待,请求1完成后调用dispatch_semaphore_signal ,信号量不再为0,接着执行请求2,signal wait成对出现
参照 : GCD控制