在后台NSURLSession中管理活动任务的数量 [英] Manage the number of active tasks in a background NSURLSession

查看:52
本文介绍了在后台NSURLSession中管理活动任务的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎在背景NSURLSession上排队太多任务(例如数百个)时,它不能很好地工作.您如何才能将排队的任务的数量保持在一个小的固定数量(例如10个)上?

It seems that when you enqueue too many tasks (say, hundreds) on a background NSURLSession, it doesn't work well. How can you keep the number of enqueued tasks at a small fixed number, say 10?

推荐答案

在负责排队任务的类中,有一个ivar来跟踪活动任务,例如

In the class that is responsible for enqueueing tasks, have a ivar to track the active tasks, e.g.

// In MySessionWrapper.m

@interface MySessionWrapper () {
    NSMutableSet *activeTaskIds;
}
@end

排队任务时,将其ID添加到该集合中:

When you enqueue a task, you add its ID to that set:

[activeTaskIds addObject:@([task taskIdentifier])]

当您收到didComplete回调时,请删除ID,并且活动任务的数量低于您的ID. 目标,您添加更多任务:

When you get a didComplete callback, you remove the ID, and if the number of active tasks falls below your target, you add more tasks:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    // other stuff
    [activeTaskIds removeObject:@([task taskIdentifier])]

    if ([activeTaskIds count] < NUMBER) {
        // add more tasks
    }
}

此系统现在对我有用.

这篇关于在后台NSURLSession中管理活动任务的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆