[英]NSURLSessionDataTask causes high CPU usage
I'm using a NSURLSessionDataTask
to feed data into an audio stream in the background (not really relevant in this case). 我正在使用NSURLSessionDataTask
将数据提供给后台的音频流(在这种情况下并不真正相关)。
The problem I'm encountering happens with just the downloading code - I've isolated this and simply discard the data, so no other parts of the system are affecting it. 我遇到的问题只发生在下载代码中 - 我已经将其隔离并简单地丢弃了数据,因此系统的其他部分都没有影响它。
I've observed that if I create the NSURLSession
with a config ( NSURLSessionConfiguration
) created using backgroundSessionConfigurationWithIdentifier
then the CPU usage while downloading is low (<5%). 我已经观察到,如果我创建NSURLSession
与一个配置( NSURLSessionConfiguration
)使用创建backgroundSessionConfigurationWithIdentifier
则CPU使用,同时下载是低的(<5%)。 Although this works (95% of the time), I believe it's not a supported configuration. 虽然这有效(95%的时间),但我认为它不是受支持的配置。 I also only need this to work when the app is in the foreground. 当应用程序在前台时,我也只需要这个工作。
So, instead, I create the NSURLSession
with a config created using ephemeralSessionConfiguration
, this also stops it using the disk as a background cache and should therefore use the least CPU. 因此,我使用ephemeralSessionConfiguration
创建了一个配置创建NSURLSession
,这也使用磁盘作为后台缓存来阻止它,因此应该使用最少的CPU。 However, in this scenario CPU usage rockets to between 70% & 80%. 但是,在这种情况下,CPU使用率会上升到70%到80%之间。
The same high CPU usage also occurs with config created using defaultSessionConfiguration
or even getting the shared NSURLSession
using [NSURLSession sharedSession]
. 使用defaultSessionConfiguration
创建的配置甚至使用[NSURLSession sharedSession]
获取共享NSURLSession
时,也会出现相同的高CPU使用率。
The data throughput is unchanged between each scenario - just not running in the background causes high CPU usage. 每种方案之间的数据吞吐量保持不变 - 只是不在后台运行会导致高CPU使用率。
I'm running on iOS 9.1 using SDK 9.1. 我使用SDK 9.1在iOS 9.1上运行。 It happens in both the simulator and on-device. 它发生在模拟器和设备上。
Update 16th Nov - As George pointed out, it appears then the didReceiveData method is thrashed. 11月16日更新 - 正如乔治所指出的,然后看起来didReceiveData方法被打破了。 The only way I've found to deal with this is to add in a call to 我发现处理这个问题的唯一方法是添加一个调用
[NSThread sleepForTimeInterval:0.25];
which seems pretty drastic, but takes the CPU from around 60-80% when downloading, to around 10-12%. 这似乎相当激烈,但下载时CPU从大约60-80%,到10-12%左右。 The download is running in it's own thread, so it's only the download that is slowed down. 下载正在它自己的线程中运行,因此只有下载才会减慢。 In fact, it's not really slowed down - the didReceiveData
just receives data in much larger chunks. 事实上,它并没有真正放慢速度 - didReceiveData
只是以更大的块接收数据。 In my app this doesn't matter. 在我的应用程序中这没关系。
您应该将NSURLSession
的delegateQueue
设置为低优先级队列(即dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
。我假设问题不在于处理实际上需要更多的CPU,而是因为它正在调度的队列而更频繁地发生是高度优先的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.