我想运行一个带有后台代码的for loop
,一旦它完成了对每个项目的迭代,就会发生一些事情。要在没有背景代码的情况下做到这一点很简单,比如:
for aString: String in strings {
if string.utf8Length < 4 {
continue
}
//Some background stuff
}
//Something to do upon completion
但在其中包含背景代码意味着在完成时执行的代码在处理所有项目之前执行。
for aString: String in strings {
if string.utf8Length < 4 {
continue
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
//Some background stuff
}
}
//Something to do upon completion
我想知道是否有可能这样做。
考虑使用调度组。这提供了一种机制,可以在调度的任务完成时通知您。因此,与其使用dispatch_async
,不如使用dispatch_group_async
:
let group = dispatch_group_create();
for aString: String in strings {
if aString.utf8Length >= 4 {
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
//Some background stuff
}
}
}
dispatch_group_notify(group, dispatch_get_main_queue()) {
// whatever you want when everything is done
}
仅供参考,这里有一个相同想法的操作队列呈现(尽管它限制了并发操作的数量)。
let queue = NSOperationQueue()
queue.name = "String processing queue"
queue.maxConcurrentOperationCount = 12
let completionOperation = NSBlockOperation() {
// what I'll do when everything is done
}
for aString: String in strings {
if aString.utf8Length >= 4 {
let operation = NSBlockOperation() {
// some background stuff
}
completionOperation.addDependency(operation)
queue.addOperation(operation)
}
}
queue.addOperation(completionOperation)