ios - 多线程在swift ios中并行执行多个任务

标签 ios swift multithreading swift4 dispatch-queue

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

并发队列---->

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 将自己并发管理您的任务。

关于ios - 多线程在swift ios中并行执行多个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50042458/

相关文章:

ios - 可重用的 TableViewCell 加载旧图像

ios - 如何自定义 UIActivityViewController 以仅包含自定义 UIActivity 类型?

swift - 更新标签时 Pickerview 滞后

multithreading - std::thread C++ 11 无法解释为什么

c# - Thread.Sleep() 在连续循环中的影响

iphone - Obj-c,在没有核心数据的情况下,执行许多 SQLite 插入/更新查询的最快方法是什么?

ios - View Controller 内的 UITable View ,不随委托(delegate)和数据源实现而改变

swift - 有人可以帮助将 URLSession 从 Swift 转换为 Kotlin

Python 和线程 : instance has no __call__ method

ios - collection view indexpathforitematpoint item