如果在循环中使用dispatch_after,如何知道所有已分派的任务是否已完成?

时间:2016-07-01 06:07:03

标签: objective-c swift grand-central-dispatch

直观地,我尝试过这样的事情:

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
for i in 0..<10 {
    CATransaction.begin()

    let now = DISPATCH_TIME_NOW
    CATransaction.setCompletionBlock {
        var delay = dispatch_time(now, 0)
        dispatch_after(delay, dispatch_get_main_queue(), {
            myfunc()
            dispatch_semaphore_signal(semaphore)
        })
    }

    CATransaction.commit()
}

for i in 0..<10 {
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
}

//task will be executed after 10 jobs are completed.

然而,似乎 dispatch_semaphore_wait 实际阻止 dispatch_after 被执行。如何等待所有10个异步作业完成?

谢谢!

1 个答案:

答案 0 :(得分:3)

您应该使用调度组,如以下示例所示。确保匹配进入/离开调用的次数,否则通知块中的代码将永远不会被执行。

let dispatchGroup = dispatch_group_create()

for _ in 0..<10 {
    dispatch_group_enter(dispatchGroup)

    // Do some async tasks
    let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))

    dispatch_after(delay, dispatch_get_main_queue(), {
        self.myfunc()
        dispatch_group_leave(dispatchGroup)
    })
}

dispatch_group_notify(dispatchGroup, dispatch_get_main_queue()) {
    // The code here will run after all tasks are completed
}