Skip to content

Instantly share code, notes, and snippets.

@beefon
Last active February 3, 2020 08:21
Show Gist options
  • Save beefon/0d5dbd6bffc0775bfd0fbed0785daecd to your computer and use it in GitHub Desktop.
Save beefon/0d5dbd6bffc0775bfd0fbed0785daecd to your computer and use it in GitHub Desktop.
NSOperationQueue + NSURLSession = no network activity
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")
@vakhidbetrakhmadov
Copy link

vakhidbetrakhmadov commented Feb 1, 2020

Also looks like compiler flattens out the nested thread dispatching

Or even more probable than that, is that URLSessionDataTasks 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)

@beefon
Copy link
Author

beefon commented Feb 3, 2020

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