0

通常我可以DispatchGroup用来跟踪多个 Dispatch 任务中的任务。但是为了确保 DispatchGroup正常工作,group.notify必须在group.enter为所有 s 调用所有tasks 之后调用该方法。

现在的问题是,我有一个递归,并且在递归中它创建了更多task的 s,我想确保所有的tasks都完成。正如我之前提到的,DispatchGroup.notify如果它比所有group.enter. 在这种递归情况下,您将不知道最后一次group.enter调用是什么时候。

简单示例:

func findPath(node: Node) {
  if !node.isValid { return }
  queue.async { //concurrent queue
    findPath(node.north)
  }
  queue.async {
    findPath(node.west)
  }
  queue.async {
    findPath(node.south)
  }
  queue.async {
    findPath(node.east)
  }
}

这是最简单的例子,在我的例子中,有更多的异步块,比如图像获取、网络 api 调用等。我如何确保findPath这个例子中的函数完全被 Dispatch 队列中的所有任务完成?

4

1 回答 1

2

在调用最后一个 dispatchGroup.leave 之前,不会调用与 dispatchGroup.notify 关联的闭包,因此您在异步任务enter 之外和leave 内部调用

就像是:

func findPath(node: Node) {
  if !node.isValid { return }
  dispatchGroup.enter()
  queue.async { //concurrent queue
    findPath(node.north)
    dispatchGroup.leave()
  }

  dispatchGroup.enter()
  queue.async {
    findPath(node.west)
    dispatchGroup.leave()
  }

  dispatchGroup.enter()
  queue.async {
    findPath(node.south)
    dispatchGroup.leave()
  }

  dispatchGroup.enter()
  queue.async {
    findPath(node.east)
    dispatchGroup.leave()
  }
}


func findPaths(startNode: Node) {
    findPath(node: startNode)
    dispatchGroup.notify {
        print("All done")
    }
}
于 2018-09-07T08:11:16.620 回答