如何等待所有NSOperations完成?

安德烈·M。

我有以下代码:

func testFunc(completion: (Bool) -> Void) {
    let queue = NSOperationQueue()
    queue.maxConcurrentOperationCount = 1

    for i in 1...3 {
        queue.addOperationWithBlock{
            Alamofire.request(.GET, "https://httpbin.org/get").responseJSON { response in
                switch (response.result){
                case .Failure:
                    print("error")
                    break;
                case .Success:
                    print("i = \(i)")
                }
            }
        }
        //queue.addOperationAfterLast(operation)
    }
    queue.waitUntilAllOperationsAreFinished()
    print("finished")
}

输出为:

finished
i = 3
i = 1
i = 2

但我期望以下几点:

i = 3
i = 1
i = 2
finished

那么,为什么queue.waitUntilAllOperationsAreFinished()不要等待?

奥兹古尔

您添加到队列中的每个操作都会立即执行,因为Alamofire.request只需返回即可,而无需等待响应数据。

此外,那里可能会出现死锁。由于responseJSON默认情况下块是在主队列中执行的,因此通过调用waitUntilAllOperationsAreFinished阻塞主线程将完全阻止其执行完成块。

首先,为了解决死锁问题,您可以告诉Alamofire在不同的队列中执行完成块,其次,可以用于dispatch_group_t对异步HTTP请求的数量进行分组,并使主线程一直等待,直到该组中的所有这些请求为止完成执行:

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
let group = dispatch_group_create()
for i in 1...3 {
  dispatch_group_enter(group)
  Alamofire.request(.GET, "https://httpbin.org/get").responseJSON(queue: queue, options: .AllowFragments) { response in
    print(i)
    dispatch_async(dispatch_get_main_queue()) {
      // Main thread is still blocked. You can update the UI here but it will take effect after all HTTP requests are finished.
    }
    dispatch_group_leave(group)
  }
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
print("finished")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章