GCD让我们创建组,这些组允许你把任务放到一个位置,然后全部运行,运行结束后
Tags: dispatch_async, dispatch_group_t, GCD
会从 GCD 收到一个通知。这一点有很多有价值的用途。例如,假设你有一个 UI-Base APP,想在 UI 上重新加载组件。你有一个表格视图,一个滚动视图,一个图片视图,就要 用这些方法加载这些组建的内容.
在 GCD 中使用组的时候你应该知道 4 个函数:
dispatch_group_create
创建一个组句柄。一旦你使用完了这个组句柄,应该使用 dispatch_release 函数将其释 放。
dispatch_group_async
在一个组内提交一个代码块来执行。必须明确这个代码块属于哪个组,必须在哪个派送队列上执行。
dispatch_group_notify
允许你提交一个 Block Object。一旦添加到这个组的任务完成执行之后,这个 Block Object 应该被执行。这个函数也允许你明确执行 Block Object 的分派队列。
dispatch_release这个函数释放那任何一个你通过 dispatch_group_create 函数创建的分派小组。
1、dispatch_group_async
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
dispatch_group_t taskGroup=dispatch_group_create();
dispatch_queue_t mainQueue1=dispatch_get_main_queue();
//reload the table view on the main queue
dispatch_group_async(taskGroup, mainQueue1, ^{
//method 1
NSLog(@"method1—–");
});
dispatch_group_async(taskGroup, mainQueue1, ^{
//method 2
NSLog(@"method2—-");
});
//at the end when we are done,dispatch the following block
dispatch_group_notify(taskGroup, mainQueue1, ^{
NSLog(@"finished");
[[[UIAlertView alloc] initWithTitle:@"Finished"
message:@"All tasks are finished" delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
});
//we are done with the group
dispatch_release(taskGroup);
|
2、也可以分派异步的 C 函数到一个分派组来使用 dispatch_group_async_f 函数
1
2
3
4
5
6
7
8
9
10
11
|
dispatch_group_t taskGroup = dispatch_group_create();
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_group_async_f(taskGroup, mainQueue,
(__bridge void *)self, reloadAllComponents);
/* At the end when we are done, dispatch the following block */ dispatch_group_notify(taskGroup, mainQueue, ^{
/* Do some processing here */[[[UIAlertView alloc] initWithTitle:@"Finished"
});
/* We are done with the group */
dispatch_release(taskGroup);
|
二、用 GCD 构建自己的分派队列
利用 GCD,你可以创建你自己的串行分派队列,串行调度队列按照先入先出(FIFO)的原则运行它们的任务。然而,串行队列上的异步任务不会在主 线程上执行,这就使得串行队列极需要并发 FIFO 任务。所有提交到一个串行队列的同步 任务会在当前线程上执行,在任何可能的情况下这个线程会被提交任务的代码使用。但是提 交到串行队列的异步任务总是在主线程以外的线程上执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
dispatch_queue_t firstSerialQueue = dispatch_queue_create("com.pixolity.GCD.serialQueue1", 0); dispatch_async(firstSerialQueue, ^{
NSUInteger counter = 0;
for (counter = 0; counter < 5; counter++){
NSLog(@"First iteration, counter = %lu", (unsigned long)counter); }
});
dispatch_async(firstSerialQueue, ^{
NSUInteger counter = 0;
for (counter = 0;counter < 5;counter++){
NSLog(@"Second iteration, counter = %lu", (unsigned long)counter);
} });
dispatch_async(firstSerialQueue, ^{
NSUInteger counter = 0;
for (counter = 0;counter < 5;counter++){
NSLog(@"Third iteration, counter = %lu", (unsigned long)counter);
} });
dispatch_release(firstSerialQueue);
|