URLSession URLSessionDataTask中的快速内存无限增加

时间:2019-06-26 11:33:31

标签: swift urlsession nsurlsessiondatatask

我正在循环运行请求,发现内存使用量无限制地增长

我认为URLSessionDataTask对象不是URLSession释放的

我的代码如下

let base = "http://myserver.com"

let group = DispatchGroup()

// 10 requests in parallel
let semaphore = DispatchSemaphore(value: 10)

func request(s: String) {
  var c = URLComponents(string: base)!
  c.queryItems = [URLQueryItem(name: "uid", value: s)]
  let url = c.url!

  var request = URLRequest(url: url)
  let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
    semaphore.signal()
    if let data = data {
      let json = String(data: data, encoding: .utf8)
      print("\(url) \(String(describing: json))")
    }
  }
  semaphore.wait()
  dataTask.resume()
}



// file with million ids
let fileName = "ids.txt"


let contents = try String(contentsOfFile: fileName)
let lines = contents.components(separatedBy: .newlines)

lines.forEach { (s) in
  request(s: s) // make a request for each
}

编辑

每条评论我都尝试用autorelease换行,但仍会增加内存

lines.forEach { (s) in
    autoreleasepool {
      request(s: s)
    }
  }

0 个答案:

没有答案