dispatch_async 与 dispatch_get_global_queue 区别

dispatch_async ,dispatch_get_global_queue和 dispatch_get_main_queue的区别

dispatch_async 函数会将传入的block块放入指定的queue里运行。这个函数是异步的,这就意味着它会立即返回而不管block是否运行结束(在主队列中除外,在主队列中不会开启新线程,会串行执行任务)。因此,我们可以在block里运行各种耗时的操作(如网络请求) 而同时不会阻塞UI线程。
dispatch_get_global_queue 会获取一个全局队列,我们姑且理解为系统为我们开启的一些全局线程。我们用priority指定队列的优先级,而flag作为保留字段备用(一般为0)。
dispatch_get_main_queue 会返回主队列,也就是UI队列。它一般用于在其它队列中异步完成了一些工作后,需要在UI队列中更新界面。
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:datawaitUntilDone:YES];
})
}
dispatch_async 会向kBgQueue队列中添加新的任务去执行,这里kBgQueue队列使用dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)获得

datawaitUntilDone:这个参数设置为YES和NO的区别:
设置为YES:只有当这个线程执行完毕,才会接着往下执行,否则一直等待
设置为NO:不管这个线程有没有执行完毕,都可以继续往下执行

Dispatch Queues

Dispatch Queues从使用的角度将更像另一种形式的Operation Queues, 只是 Operation Queuse是用Objective_C的Dispatch Queues是C的dispatch Queues有serial Queues 也被称为私有dispatch Queues,一个时间只能运行一个task,顺序运行dispatch_queue_t queue;
还有一种就是Concurrent Queues每个程序系统自动提供了3个Concurrent Queue

 dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
 dispatch_queue_t aHQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
 dispatch_queue_t aLQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);  

啥意思一看就明白,3个优先级别的concurrent queues
最后一个特殊的Dispatch Queue就是main dispatch Queue 也是程序启动自动生成dispatch_queue_t mainQueue = dispatch_get_main_queue();

concurrent queues和main queue 都是由系统生成而且 dispatch_suspend, dispatch_resume, dispatch_set_context,这些函数对他们无效

但是我们的应用不是简单的同步也异步的运行,应用经常是混合的
比如我们要task1 task2 task3 都运行完成后才能异步运行task4 task5 task6我们该怎么做呢?这里我们可以引入group的概念

dispatch_queue_t aDQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, aDQueue, ^{
    NSLog(@"task 1 \n");
});

dispatch_group_async(group, aDQueue, ^{
    NSLog(@"tast 2 \n");
});

dispatch_group_async(group, aDQueue, ^{
    NSLog(@"tast 3 \n");
});

NSLog(@"please wait 1 2 3 \n");

dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

NSLog(@"task 1 2 3 finished \n");
group = dispatch_group_create();
dispatch_group_async(group, aDQueue, ^{
    NSLog(@"task 4 \n");
});

dispatch_group_async(group, aDQueue, ^{
    NSLog(@"task 5 \n");
});

dispatch_group_async(group, aDQueue, ^{
    NSLog(@"task 6 \n");
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"task 4 5 6 finished \n");

你可能感兴趣的:(dispatch_async 与 dispatch_get_global_queue 区别)