2

我知道队列的创建并且能够执行单个任务,但是我如何并行执行多个任务。

并发队列---->

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
}

所有都是异步的,但是我如何一次执行多个方法我应该如何快速编码。

4

1 回答 1

6

如果你有一个调用方法的 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 将自己同时管理您的任务。

于 2018-04-26T12:25:29.097 回答