陈斌彬的技术博客

Stay foolish,stay hungry

Dispatch_async 和 Dispatch_sync

dispatch_sync(),同步添加操作。他是等待添加进队列里面的操作完成之后再继续执行。

dispatch_queue_t concurrentQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
NSLog(@"1");
dispatch_sync(concurrentQueue, ^(){
    NSLog(@"2");
    [NSThread sleepForTimeInterval:10];
    NSLog(@"3");
});
NSLog(@"4");

输出 :

11:36:25.313 GCDSeTest[544:303] 1

11:36:25.313 GCDSeTest[544:303] 2

11:36:30.313 GCDSeTest[544:303] 3//模拟长时间操作

11:36:30.314 GCDSeTest[544:303] 4

dispatch_async ,异步添加进任务队列,它不会做任何等待

dispatch_queue_t concurrentQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
NSLog(@"1");
dispatch_async(concurrentQueue, ^(){
    NSLog(@"2");
    [NSThread sleepForTimeInterval:5];
    NSLog(@"3");
});
NSLog(@"4");

输出:

 11:42:43.820 GCDSeTest[568:303] 1

 11:42:43.820 GCDSeTest[568:303] 4

 11:42:43.820 GCDSeTest[568:1003] 2

 11:42:48.821 GCDSeTest[568:1003] 3//模拟长时间操作时间