zoukankan      html  css  js  c++  java
  • GCD调度组、自定义队列来实现多个下载任务

    #define KURL1 @"http://img0.imgtn.bdimg.com/it/u=79920747,2237302485&fm=90&gp=0.jpg"
    #define KURL2 @"http://img5.imgtn.bdimg.com/it/u=2983485216,1361143125&fm=90&gp=0.jpg"
    #import "ViewController.h"
    
    @interface ViewController ()
    {
        dispatch_queue_t myQueue;
    }
    @property (weak, nonatomic) IBOutlet UILabel *remindLabel;
    @property (weak, nonatomic) IBOutlet UIImageView *firstImageView;
    @property (weak, nonatomic) IBOutlet UIImageView *secondImageView;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        //自定义队列
        myQueue=dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
    }
    
    
    - (IBAction)sendBtnClick:(UIButton *)sender
    {
        //创建调度组
        dispatch_group_t myGroup=dispatch_group_create();
        
        //延时执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC*2)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_group_async(myGroup, myQueue, ^{
                
                dispatch_async(myQueue, ^{
                    
                    NSData *firstData=[NSData dataWithContentsOfURL:[NSURL URLWithString:KURL1]];
                    //主队列刷新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        _firstImageView.image=[UIImage imageWithData:firstData];
                        
                    });
                    
                });
            });
            
            dispatch_group_async(myGroup, myQueue, ^{
                
                dispatch_async(myQueue, ^{
                    
                    NSData *secondData=[NSData dataWithContentsOfURL:[NSURL URLWithString:KURL2]];
                    //主队列刷新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        _secondImageView.image=[UIImage imageWithData:secondData];
                        
                    });
                    
                });
                
            });
            
        });
        
        //异步函数监听调度组里面的任务完成后刷新UI
        dispatch_group_notify(myGroup, myQueue, ^{
            _remindLabel.text=@"下载完成";
            
        });
        /*
        //同步函数 主线程阻塞 主要用于数据库操作
        dispatch_group_wait(myGroup, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC)));
         _remindLabel.text=@"下载完成";
         */
    }
  • 相关阅读:
    go-elasticsearch 来自官方的 golang es client
    nginx unit nodejs 模块试用(续)
    WebSocket-Over-HTTP Protocol
    pushpin Server-sent events && openresty 集成试用
    Rendering on the Web
    pushpin openresty 集成试用
    100 webhook implementations
    streamdataio 实时数据分发平台
    Generic Realtime Intermediary Protocol
    Pushpin How it works
  • 原文地址:https://www.cnblogs.com/thbbsky/p/4376338.html
Copyright © 2011-2022 走看看