简单的辅助类,它可以简化Swift中使用并发方法时的复杂性。
ROConcurrency可通过CocoaPods获取。要安装它,只需将以下行添加到您的Podfile中
pod "ROConcurrency"
使用以下类Barrier,您可以定义一组执行为异步的任务。屏障会跟踪已执行的任务,如果所有任务都已完成,您可以定义一个afterTask,在该任务完成后执行。
创建任务
var task_one = Task {
sleep(3)
println("Task one is doing some stuff..")
}
var task_two = Task {
println("Task two is doing some stuff..")
}
var task_third = Task {
println("Task three is doing some stuff..")
}
var afterTask = Task {
println("I should get executed at the end of all the other requests")
}
然后使用以下代码行创建屏障
var barrier = Barrier(tasks: [task_one, task_two, task_third], afterTask:afterTask)
如果想要激活任务执行的详细日志记录,可以将参数verbose设置为true(默认为false)。
var barrier = Barrier(tasks: [task_one, task_two, task_third], afterTask:afterTask, verbose:true)
可以使用startTasks
方法启动任务
barrier.startTasks()
通常您已经有异步任务,使用上述方法时,无法通知屏障异步任务已完成。这就是TaskComplex和BarrierComplex类的作用。在TaskComplex块中,您可以封装已异步执行的方法,并在异步块执行的末尾添加finished()的调用。其余部分与上述Barrier类的概念完全相同。
var taskDownload = TaskComplex { (finished) -> () in
// Do something asynchronously and then at the end call the finished block to notify the barrier that it's finished
finished()
}
var taskCompress = TaskComplex { (finished) -> () in
// Do something else
finished()
}
var notifiyEveryoneAtTheEnd = TaskComplex { (finished) -> () in
// Notify everyone
finished()
}
var barrierComplex = BarrierComplex(tasks: [taskDownload, taskCompress], afterTask: notifiyEveryoneAtTheEnd, verbose: true)
barrierComplex.startTasks()
The MIT License (MIT)
Copyright (c) 2015 Robin Oster (http://prine.ch)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Robin Oster, [email protected]