美文网首页
AFNetworking+GCD处理并发问题

AFNetworking+GCD处理并发问题

作者: 默默_David | 来源:发表于2017-11-02 16:16 被阅读98次

    原文地址:http://blog.csdn.net/pianzhidenanren/article/details/52571853 

    我们在编程的时候会经常会出现这样的需求:同时请求几个接口回调成功以后在统一刷新UI,解决这个问题的方法有很多今天我们就说明下GCD下解决的方式。

    GCD的leave和enter

    我们利用dispatch_group_t创建队列组,手动管理group关联的block运行状态,进入和退出group的次数必须匹配。

    //1.创建队列组

    dispatch_group_t group = dispatch_group_create();

    //2.创建队列

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

    //3.添加请求

    dispatch_group_async(group, queue, ^{

    dispatch_group_enter(group);

    [HomeRequestgetPointBuyAllConfigurationStrategyType:_dataTypesuccess:^(NSInteger code,NSDictionary*dict) {

    dispatch_group_leave(group);

    }failuer:^(NSInteger code,NSString*message) {

    dispatch_group_leave(group);

    }];

    });

    dispatch_group_async(group, queue, ^{

    dispatch_group_enter(group);

    [HomeRequestgetStockLeverRiskStockCode:_buyingStrategyModel.stockCodestrategyType:_dataTypesuccess:^(NSInteger code,NSDictionary*dict) {

    dispatch_group_leave(group);

    }failuer:^(NSInteger code,NSString*message) {

    dispatch_group_leave(group);

    }];

    });

    //4.队列组所有请求完成回调刷新UI

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{

    NSLog(@"model:%f",_buyingStrategyModel.leverrisk);

    });

    GCD的信号量dispatch_semaphore_t

    这种方式有点类似于通知模式,是利用监听信号量来发送消息以达到并发处理的效果,我们来看看代码:

    //创建信号量

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group, queue, ^{

    [HomeRequestgetPointBuyAllConfigurationStrategyType:_dataTypesuccess:^(NSInteger code,NSDictionary*dict) {

    dispatch_semaphore_signal(semaphore);

    }failuer:^(NSInteger code,NSString*message) {

    dispatch_semaphore_signal(semaphore);

    }];

    });

    dispatch_group_async(group, queue, ^{

    [HomeRequestgetStockLeverRiskStockCode:_buyingStrategyModel.stockCodestrategyType:_dataTypesuccess:^(NSInteger code,NSDictionary*dict) {

    dispatch_semaphore_signal(semaphore);

    }failuer:^(NSInteger code,NSString*message) {

    dispatch_semaphore_signal(semaphore);

    }];

    });

    dispatch_group_notify(group, queue, ^{

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    NSLog(@"信号量为0");

    });

    这两种方式都可以达到并发处理的效果,当然还有其他方式,大家一起学习吧!

    相关文章

      网友评论

          本文标题:AFNetworking+GCD处理并发问题

          本文链接:https://www.haomeiwen.com/subject/byoyuxtx.html