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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.