2 multithreading ios swift swift4 dispatch-queue
我知道队列的创建并能够执行单个任务,但我如何并行执行多个任务。
并发队列---->
let concurrentQueue = DispatchQueue(label: "com.some.concurrentQueue", attributes: .concurrent)
concurrentQueue.async {
//executable code
}
Run Code Online (Sandbox Code Playgroud)
无优先级的BackgroundQueue 默认--->
DispatchQueue.global().async {
//executable code
}
Run Code Online (Sandbox Code Playgroud)
具有优先级的后台队列---->
DispatchQueue.global(qos: .userInitiated).async { //.userInteractive .background .default .unspecified
//executable code
}
Run Code Online (Sandbox Code Playgroud)
回到主队列---->
DispatchQueue.main.async {
//executable code
}
Run Code Online (Sandbox Code Playgroud)
所有都是异步的,但是我如何一次执行多个方法我应该如何快速编码。
如果你有一个调用一个方法的 for 循环方法,并且你想同时调用这个方法,那么只需使用这个:
DispatchQueue.concurrentPerform(iterations: Int, execute: { (count) in
doSomethingFor(count: count)
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您有一些要调用并发的个人方法,请执行以下操作:
let concurrentQueue = DispatchQueue(label: "com.some.concurrentQueue", attributes: .concurrent)
concurrentQueue.async {
//executable code
myFirstMethod()
}
concurrentQueue.async {
//executable code
mySecondMethod()
}
Run Code Online (Sandbox Code Playgroud)
这种方式 concurrentQueue,将同时管理您的任务本身。
| 归档时间: |
|
| 查看次数: |
3662 次 |
| 最近记录: |