派遣集团

DispatchGroup 允许工作的聚合同步。你可以使用它们提交多个不同的工作项并跟踪它们何时完成,即使它们可能在不同的队列上运行。在完成所有指定任务之前无法进行此操作时,此行为很有用。

这可能有用的场景是,如果你有多个 webservice 调用,所有这些调用都需要在继续之前完成。例如,你需要下载需要由某个函数处理的多组数据。在调用函数处理所有接收的数据之前,必须等待所有 Web 服务完成。

Swift 3

func doLongTasksAndWait () {
    print("starting long running tasks")
    let group = DispatchGroup()          //create a group for a bunch of tasks we are about to do
    for i in 0...3 {                     //launch a bunch of tasks (eg a bunch of webservice calls that all need to be finished before proceeding to the next ViewController)
        group.enter()                    //let the group know that something is being added
        DispatchQueue.global().async {   //run tasks on a background thread
            sleep(arc4random() % 4)      //do some long task eg webservice or database lookup (here we are just sleeping for a random amount of time for demonstration purposes)
            print("long task \(i) done!")
            group.leave()                //let group know that the task is finished
        }
    }
    group.wait()                         //will block whatever thread we are on here until all the above tasks have finished (so maybe dont use this function on your main thread)
    print("all tasks done!")
}

或者,如果你不想等待组完成,而是想在所有任务完成后运行一个函数,请使用 notify 函数代替 group.wait()

group.notify(queue: DispatchQueue.main) { //the queue: parameter is which queue this block will run on, if you need to do UI updates, use the main queue
    print("all tasks done!")              //this will execute when all tasks have left the group
}

输出示例:

starting long running tasks
long task 0 done!
long task 3 done!
long task 1 done!
long task 2 done!
all tasks done!

有关详细信息,请参阅 Apple Docs 或相关主题