博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
dispatch_async 和dispatch_sync
阅读量:6616 次
发布时间:2019-06-25

本文共 7326 字,大约阅读时间需要 24 分钟。

hot3.png

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];    button.frame = CGRectMake(10, 10, 100, 100);    button.backgroundColor = [UIColor brownColor];    [self.view addSubview:button];    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    dispatch_async(concurrentQueue, ^{        NSLog(@"111111111111111 %@",[NSThread currentThread]);        __block UIImage *image = nil;        dispatch_sync(concurrentQueue, ^{  //@1dispatch_sync            NSLog(@"22222222222222 %@",[NSThread currentThread]);            //download image            NSString *urlString = @"http://images.apple.com/v/macbook-pro/f/images/loupe.png";            NSURL *url = [NSURL URLWithString:urlString];            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];            NSError *downloadError = nil;            NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];            if (downloadError == nil && imageData != nil) {                image = [UIImage imageWithData:imageData];            }else if(downloadError != nil){                NSLog(@"Error Happened = %@",downloadError);            }else{                NSLog(@"No data could get download from URL.");            }        });        dispatch_sync(concurrentQueue, ^{   //@2//dispatch_sync            //show image here            NSLog(@"33333333333 %@",[NSThread currentThread]);            if (image != nil) {                UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];                [imageView setImage:image];               // [imageView setContentMode:UIViewContentModeScaleAspectFill];                [self.view addSubview:imageView];            }else{                NSLog(@"Image isn't downloaded. Nothing to display.");            }        });    });}@end

输出如下:

2015-03-31 15:13:59.848 iOSCookbook 7.7[21442:599814] 111111111111111 <NSThread: 0x7ff57ae02480>{number = 2, name = (null)}

2015-03-31 15:13:59.851 iOSCookbook 7.7[21442:599814] 22222222222222 <NSThread: 0x7ff57ae02480>{number = 2, name = (null)}
2015-03-31 15:13:59.992 iOSCookbook 7.7[21442:599814] 33333333333 <NSThread: 0x7ff57ae02480>{number = 2, name = (null)}

第二种测试:

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];    button.frame = CGRectMake(10, 10, 100, 100);    button.backgroundColor = [UIColor brownColor];    [self.view addSubview:button];    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    dispatch_async(concurrentQueue, ^{        NSLog(@"111111111111111 %@",[NSThread currentThread]);        __block UIImage *image = nil;        dispatch_async(concurrentQueue, ^{  //@1dispatch_async            NSLog(@"22222222222222 %@",[NSThread currentThread]);            //download image            NSString *urlString = @"http://images.apple.com/v/macbook-pro/f/images/loupe.png";            NSURL *url = [NSURL URLWithString:urlString];            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];            NSError *downloadError = nil;            NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];            if (downloadError == nil && imageData != nil) {                image = [UIImage imageWithData:imageData];            }else if(downloadError != nil){                NSLog(@"Error Happened = %@",downloadError);            }else{                NSLog(@"No data could get download from URL.");            }        });        dispatch_sync(concurrentQueue, ^{   //@2//dispatch_sync            //show image here            NSLog(@"33333333333 %@",[NSThread currentThread]);            if (image != nil) {                UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];                [imageView setImage:image];               // [imageView setContentMode:UIViewContentModeScaleAspectFill];                [self.view addSubview:imageView];            }else{                NSLog(@"Image isn't downloaded. Nothing to display.");            }        });    });}@end

将1@处改为dispatch_async

输出如下:

2015-03-31 15:16:13.143 iOSCookbook 7.7[21471:600996] 111111111111111 <NSThread: 0x7f8769f01670>{number = 2, name = (null)}

2015-03-31 15:16:13.145 iOSCookbook 7.7[21471:600996] 33333333333 <NSThread: 0x7f8769f01670>{number = 2, name = (null)}
2015-03-31 15:16:13.145 iOSCookbook 7.7[21471:600996] Image isn't downloaded. Nothing to display.
2015-03-31 15:16:13.145 iOSCookbook 7.7[21471:600997] 22222222222222 <NSThread: 0x7f8769e29ee0>{number = 3, name = (null)}

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];    button.frame = CGRectMake(10, 10, 100, 100);    button.backgroundColor = [UIColor brownColor];    [self.view addSubview:button];    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    dispatch_async(concurrentQueue, ^{        NSLog(@"111111111111111 %@",[NSThread currentThread]);        __block UIImage *image = nil;        dispatch_sync(concurrentQueue, ^{  //@1dispatch_sync            NSLog(@"22222222222222 %@",[NSThread currentThread]);            //download image            NSString *urlString = @"http://images.apple.com/v/macbook-pro/f/images/loupe.png";            NSURL *url = [NSURL URLWithString:urlString];            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];            NSError *downloadError = nil;            NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];            if (downloadError == nil && imageData != nil) {                image = [UIImage imageWithData:imageData];            }else if(downloadError != nil){                NSLog(@"Error Happened = %@",downloadError);            }else{                NSLog(@"No data could get download from URL.");            }        });        dispatch_sync(dispatch_get_main_queue(), ^{   //@2//dispatch_sync         // dispatch_get_main_queue()          //show image here            NSLog(@"33333333333 %@",[NSThread currentThread]);            if (image != nil) {                UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];                [imageView setImage:image];               // [imageView setContentMode:UIViewContentModeScaleAspectFill];                [self.view addSubview:imageView];            }else{                NSLog(@"Image isn't downloaded. Nothing to display.");            }        });    });}@end

不知道为什么使用dispatch_get_main_queue() 比concurrentQueue要快很多!

一般的使用原则如下:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{    // 耗时的操作    dispatch_async(dispatch_get_main_queue(), ^{        // 更新界面    });});

转载于:https://my.oschina.net/u/1782374/blog/394199

你可能感兴趣的文章
Tomcat配置日志生产功能
查看>>
移植Qt与Tslib到X210开发板的体会
查看>>
Nginx + webpy 和FastCGI搭建webpy环境
查看>>
使用JdbcTemplate过程中使用到多个参数和like模糊
查看>>
解决eclipse中无法删除Tomcat服务器中的项目,报maven is required and cannot be removed from the server错误情况...
查看>>
修改页面JS 360浏览器
查看>>
尚学linux课程---3、linux网络说明
查看>>
Git 跟 GitHub 是什么关系?
查看>>
String.split()方法
查看>>
IE6下jQuery选中select的BUG
查看>>
Tensorflow在win10下的安装(CPU版本)
查看>>
嵌入式平台做深度学习算法,不可不重视的4件事
查看>>
一次优化记录
查看>>
如何调用一个数据完整的firefox浏览器
查看>>
cgroup代码浅析(2)
查看>>
会计的思考(42):会计如何转变为公司的内部财务顾问
查看>>
利用钥匙串,在应用里保存用户密码的方法
查看>>
final,finally和finalize之间的区别
查看>>
python 装饰器
查看>>
[辟谣]下蹲猛起来眼前发黑是心脏衰竭的表现?别扯了!
查看>>