派遣集團

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 或相關主題