代码之家  ›  专栏  ›  技术社区  ›  Marvin K. Bellamy

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

  •  1
  • Marvin K. Bellamy  · 技术社区  · 7 年前

    我试图做的是顺序执行一个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 回复  |  直到 7 年前
        1
  •  1
  •   Gustavo Vollbrecht    5 年前

    我更喜欢使用背景组,你可以在你的类中创建一个这样的实例: 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
                if let strongSelf = self {
                    outcome = result
                    strongSelf.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
                }
            }
        }