AFNetworking+GCD处理并发问题

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 10:36   17   0

我们在编程的时候会经常会出现这样的需求:同时请求几个接口回调成功以后在统一刷新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);
        [HomeRequest getPointBuyAllConfigurationStrategyType:_dataType success:^(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);
        [HomeRequest getStockLeverRiskStockCode:_buyingStrategyModel.stockCode strategyType:_dataType success:^(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, ^{
        [HomeRequest getPointBuyAllConfigurationStrategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
            dispatch_semaphore_signal(semaphore);
        } failuer:^(NSInteger code, NSString *message) {
            dispatch_semaphore_signal(semaphore);
        }];
    });
    dispatch_group_async(group, queue, ^{
        [HomeRequest getStockLeverRiskStockCode:_buyingStrategyModel.stockCode strategyType:_dataType success:^(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");
    });

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


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP