美文网首页
dispatch_group_t 异步并发请求网络

dispatch_group_t 异步并发请求网络

作者: JasonFive | 来源:发表于2021-04-08 17:19 被阅读0次

    一个操作是 需要同时并发 5个网络异步请求,然后最后当网络都全部请求完成后,再刷新UI

    dispatch_queue_t concurrentQueue = dispatch_queue_create("test1", DISPATCH_QUEUE_CONCURRENT);
        dispatch_group_t group = dispatch_group_create();
        for (int i = 0; i < 5; i++) {
            dispatch_group_async(group, concurrentQueue, ^{
                NSLog(@"开始--%d",i);
                dispatch_group_enter(group);
                LoginRequest *request = [[LoginRequest alloc]initWithLoginMobile:@"123" password:@"123" method:HTTPMethodGet];
                [[NetworkCenter sharedInstance] startRequestWith:request completion:^(id  _Nullable result, NSString * _Nullable error) {
                    dispatch_group_leave(group);
                    NSLog(@"结束--%d",i);
                }];
                NSLog(@"过程中--%d",i);
            });
        }
        dispatch_group_notify(group, concurrentQueue, ^{
            NSLog(@"全部结束-刷新UI");
        });
    

    结果

    2021-04-08 17:07:04.142538+0800 ws[2172:1065286] 开始--0
    2021-04-08 17:07:04.142723+0800 ws[2172:1065286] (null)
    2021-04-08 17:07:04.142853+0800 ws[2172:1065162] 开始--1
    2021-04-08 17:07:04.142956+0800 ws[2172:1065162] (null)
    2021-04-08 17:07:04.142965+0800 ws[2172:1065296] 开始--2
    2021-04-08 17:07:04.143031+0800 ws[2172:1065296] (null)
    2021-04-08 17:07:04.143189+0800 ws[2172:1065298] 开始--3
    2021-04-08 17:07:04.143255+0800 ws[2172:1065298] (null)
    2021-04-08 17:07:04.143298+0800 ws[2172:1065374] 开始--4
    2021-04-08 17:07:04.143678+0800 ws[2172:1065374] (null)
    2021-04-08 17:07:04.144462+0800 ws[2172:1065162] 过程中--1
    2021-04-08 17:07:04.144464+0800 ws[2172:1065296] 过程中--2
    2021-04-08 17:07:04.144738+0800 ws[2172:1065298] 过程中--3
    2021-04-08 17:07:04.145017+0800 ws[2172:1065374] 过程中--4
    2021-04-08 17:07:04.145248+0800 ws[2172:1065286] 过程中--0
    2021-04-08 17:07:04.406002+0800 ws[2172:1064910] 结束--3
    2021-04-08 17:07:04.406988+0800 ws[2172:1064910] 结束--2
    2021-04-08 17:07:04.408535+0800 ws[2172:1064910] 结束--1
    2021-04-08 17:07:04.410091+0800 ws[2172:1064910] 结束--4
    2021-04-08 17:07:04.457578+0800 ws[2172:1064910] 结束--0
    2021-04-08 17:07:04.457588+0800 ws[2172:1065286] 全部结束-刷新UI
    

    相关文章

      网友评论

          本文标题:dispatch_group_t 异步并发请求网络

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