swift - dispatch_async 与 dispatch_sync 在获取数据中的对比。 swift

标签 swift concurrency fetch dispatch dispatch-async

看了那么多并行和并发的帖子,我还是很迷惑什么才是正确的取数据方式。例如,在我的项目中,我有一个供用户获取数据的按钮。我的代码如下所示。

var array = [Int]()
func fetchData() {

   ....
   ....
   response(objects: [object], error: NSError?) {
       for object in objects {
           array.append(object.number) // assume object.number return an Int
       }

       // confuse here. Should I use async here because I am worry if the user 
       // click the fetchData button more than one time, the append and make 
       // function will be happened at the same time. Or, is there anything I 
       // made a wrong assumption? I guess I need a serial operation. Correct?

       dispatch_async(dispatch_get_main_queue()) {
           makeCollectionView() // using the data in array
       }
   }
}

更新

尝试运行此代码。 10000-19999 在 0-9999 之后运行。似乎第二个异步不会停止第一个异步来处理它的操作。

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    for i in 0 ..< 10000 {
        print(i)
    }
})
dispatch_async(dispatch_get_main_queue(), { () -> Void in
    for i in 10000 ..< 20000 {
         print(i)
    }
})

最佳答案

为了提高性能,任何涉及 UI 的东西都应该在主线程上运行。所以基本上:

dispatch_async(dispatch_get_main_queue()) {
       //anything that involves UI
   }

关于swift - dispatch_async 与 dispatch_sync 在获取数据中的对比。 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011078/

相关文章:

Java 并发 : Are "get(Key) for HashMap and ConcurrentHashMap equal in performance?

react-native - 我的 native 应用程序在从我的服务器错误 : "type error :Network Request Failed " 获取数据时显示错误

PHP 代码 (mysqli) 查询在特定代码后不起作用

ios - 禁用 UITableView 离屏渲染

ios - 使用 Swift 从 Parse 检索 "createdAt"和 "updatedAt"

scala - Scala 中的 Futures 真的有用吗?

ios - swift 核心数据 : How to fetch all items in array?

ios - 如何计算核心数据中的连续天数?

ios - 根据位置删除图像的ScrollView

c++ - 为什么在 C++ 中使用 std::atomic<double>、std::atomic<float> 时,compare_exchange_strong 会失败?