你如何等待主队列完成处理程序?

时间:2017-11-26 22:33:08

标签: ios swift multithreading closures completionhandler

我要做的是顺序执行for循环,在开始下一次迭代之前我等待completionHandler()。

  • 我必须等待完成处理程序在迭代之前返回
  • 保证返回完成处理程序
  • 我正在尝试同步等待优先级较低的队列

代码:

// we're on the main queue
for index in 0..<count {
    var outcome: Any?
    let semaphore = DispatchSemaphore(value: 0)
    let queue = DispatchQueue(label: "\(index) iteration")
    // this will access a UI component and wait for user to
    // enter a value that's passed to the completion handler
    funcWithCompletionHandler() { [weak self] (result) in
        outcome = result
        semaphore.signal()
    }
    // wait here for the completion handler to signal us
    queue.sync {
        semaphore.wait()
        if let o = outcome {
            handleOutcome(outcome)
        }
    }
    // now, we iterate
}

我已经尝试了很多其他的解决方案,我看到这里似乎没什么用。

1 个答案:

答案 0 :(得分:1)

我更喜欢使用后台组,您可以在类上创建它的实例,如下所示:   var group = DispatchGroup()

    DispatchQueue.global(qos: .background).async {
        self.group.wait()

       // this part will execute after the last one left
       // .. now, we iterate part
    }


    for index in 0..<count {
        var outcome: Any?
        let queue = DispatchQueue(label: "\(index) iteration")



        funcWithCompletionHandler() { [weak self] (result) in
            outcome = result
            self.group.enter() // group count = 1
        }

        queue.sync {
            if let o = outcome {
                handleOutcome(outcome)
                self.group.leave()
       // right here group count will be 0 and the line after wait will execute
            }
        }
    }