【问题标题】:Run tasks asynchronously/concurrently/parallally in iOS swift在 iOS swift 中异步/并发/并行运行任务
【发布时间】:2018-04-11 12:29:29
【问题描述】:

我怎样才能一次执行所有上述任务以提高速度。

self.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[0]) 

self.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[1]) 

self.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[2]) 

self.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[3])

【问题讨论】:

  • 发布getFullMail方法的内容
  • 您是从网络获取数据吗?如果是这样,您在应用中执行的任何操作都不太可能提高性能
  • 我建议在 for 循环中打印线程 ID 以验证您是否正在获得并发执行。调整什么可能取决于答案。

标签: ios swift swift4 grand-central-dispatch dispatch-queue


【解决方案1】:

你所追求的是 DispatchQueue concurrentPerform 上的类函数

例如:

DispatchQueue.concurrentPerform(iterations: msgIDBatches.count) { (index) in
    self.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[index])    
}

如果您要更新 UI,显然需要小心回调主队列,并确保 passingMsgIdsTofetchMsgss 是线程安全的。还值得使用time profiler 进行检查,这实际上是性能瓶颈所在。

另一个选项是OperationQueue,您可以将所有提取添加到队列并同时执行它们。

【讨论】:

    【解决方案2】:

    斯威夫特 4.1。首先创建一个并发队列

    private let concurrentPhotoQueue = DispatchQueue(label: "App_Name", attributes: .concurrent)
    

    现在将您的工作分派到并发队列

    concurrentPhotoQueue.async(flags: .barrier) { [weak self] in
                // 1
                guard let weakSelf = self else {
                    return
                }
                // 2 Perform your task here
                weakSelf.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[0])
                weakSelf.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[1])
                weakSelf.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[2])
                weakSelf.passingMsgIdsTofetchMsgss(messageIDs : msgIDBatches[3])
                // 3
                DispatchQueue.main.async { [weak self] in
                    // Update your UI here
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 2020-10-11
      • 2012-09-02
      • 1970-01-01
      相关资源
      最近更新 更多