如何等到所有 NSOperations 完成? [英] How to wait until all NSOperations is finished?

查看:59
本文介绍了如何等到所有 NSOperations 完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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() 不等待?

So, why queue.waitUntilAllOperationsAreFinished() don't wait?

推荐答案

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

Each operation you've added into queue is immediately executed because Alamofire.request simply returns without waiting for the response data.

此外,还有可能出现死锁.由于 responseJSON 块默认在主队列中执行,通过调用 waitUntilAllOperationsAreFinished 阻塞主线程将完全阻止它执行完成块.

Furthermore, there is a possibility of deadlock there. Since responseJSON block is executed within the main queue by default, blocking the main thread by calling waitUntilAllOperationsAreFinished will prevent it from executing the completion block at all.

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

First, in order to fix the deadlock issue, you can tell Alamofire to execute the completion block in a different queue, second, you can use dispatch_group_t to group the number of asynchronous HTTP requests and keep the main thread waiting till all those requests in the group finish executing:

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")

这篇关于如何等到所有 NSOperations 完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆