Last active
February 3, 2020 08:21
-
-
Save beefon/0d5dbd6bffc0775bfd0fbed0785daecd to your computer and use it in GitHub Desktop.
NSOperationQueue + NSURLSession = no network activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Dispatch | |
import Foundation | |
// If you run this playground, you will never see `Request feedback` message in console. | |
let queue = OperationQueue() | |
// but if you uncomment the line below, it suddenly starts working great | |
// queue.maxConcurrentOperationCount = 63 | |
// but if you set maxConcurrentOperationCount to 64, it stops working again | |
for _ in 0...999 { | |
queue.addOperation { | |
let group = DispatchGroup() | |
var request = URLRequest(url: URL(string: "http://example.com")!) | |
request.timeoutInterval = 10 | |
let task = URLSession.shared.dataTask(with: request) { _,_,_ in | |
print("\(Date()) Request feedback") | |
group.leave() | |
} | |
print("\(Date()) Starting request") | |
task.resume() | |
group.enter() | |
if group.wait(wallTimeout: .now() + 30) == .timedOut { | |
task.cancel() | |
print("\(Date()) Request timeout") | |
} | |
} | |
} | |
queue.waitUntilAllOperationsAreFinished() | |
print("\(Date()) Queue is empty") |
Also looks like compiler flattens out the nested thread dispatching
Or even more probable than that, is that URLSessionDataTask
s are being added to OperationQueue.current
with lower priority, but could not confirm. OperationQueue.current === queue
inside URLSessionDataTask
's completion block yields false
(may be completion queue is different)
Thanks Vakhid, I forgot to attach a link to the forum where Apple stuff has commented on this issue.
https://forums.swift.org/t/operationqueue-urlsession-no-network-activity-oob/33247
You were absolutely right, there is a shared thread pool in GCD for all queues, and that explains a lot.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, because of all operations being run first, and both
OperationQueue
andURLSessionDataTask
using the same threads-pool (limited to 64), not settingmaxConcurrentOperationCount
(that is leaving its default value -1 that probably translates to using the entire pool) means that noURLSessionDataTask
has chance to run until first 960 operations timeout.While limiting
maxConcurrentOperationCount
to 63 means that there will always be at least 1 thread in threads-pull forURLSessionDataTask
.