AFNetworking+GCD处理并发问题

我们在编程的时候会经常会出现这样的需求:同时请求几个接口回调成功以后在统一刷新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");  

    });  

你可能感兴趣的:(AFNetworking+GCD处理并发问题)