我知道队列的创建并且能够执行单个任务,但如何并行执行多个任务。
并发队列---->
let concurrentQueue = DispatchQueue(label: "com.some.concurrentQueue", attributes: .concurrent)
concurrentQueue.async {
//executable code
}
默认无优先级的BackgroundQueue--->
DispatchQueue.global().async {
//executable code
}
具有优先级的后台队列---->
DispatchQueue.global(qos: .userInitiated).async { //.userInteractive .background .default .unspecified
//executable code
}
回到主队列---->
DispatchQueue.main.async {
//executable code
}
所有都是异步的,但是我如何一次执行多个方法,我应该如何快速编码。
如果您有一个调用方法的 for 循环方法,并且您想并发调用该方法,那么只需使用:
DispatchQueue.concurrentPerform(iterations: Int, execute: { (count) in
doSomethingFor(count: count)
}
但是,如果您想并发调用某些单独的方法,只需这样做:
let concurrentQueue = DispatchQueue(label: "com.some.concurrentQueue", attributes: .concurrent)
concurrentQueue.async {
//executable code
myFirstMethod()
}
concurrentQueue.async {
//executable code
mySecondMethod()
}
这样,concurrentQueue 就会同时管理您的任务。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)