gpt4 book ai didi

ios - 为什么我们在核心数据中使用performWait?

转载 作者:行者123 更新时间:2023-12-04 15:31:54 24 4
gpt4 key购买 nike

据我们所知

  • performWait 函数同步执行上下文队列中的给定 block 。
  • 执行函数异步执行上下文队列中的给定 block 。

在我的项目中,我使用 performWait 函数来获取数据,因为我希望调用线程在返回之前等到 block 执行完毕。这是实现它的最简单方法。但后来我意识到 performWait 的工作速度很慢。然后我尝试用信号量实现自己的同步并使用 perform 函数。以下是结果:

执行等待

    let currentTime1 = getCurrentMillis()
context?.performAndWait({
....
})
let currentTime2 = getCurrentMillis()
let diff = currentTime2 - currentTime1
print("getActivities diff: " + String(diff))

执行信号量

    let currentTime1 = getCurrentMillis()
let semaphore = DispatchSemaphore(value: 0)
context?.perform({
....
semaphore.signal()
})
semaphore.wait()
let currentTime2 = getCurrentMillis()
let diff = currentTime2 - currentTime1
print("getActivities diff: " + String(diff))

getActivities 差异:1248 毫秒

getActivitiesWithSemaphore 差异:90 毫秒

好的,我知道这更容易。但是,为什么这么慢?将它用于 perform 函数还有哪些其他优势?

最佳答案

The perform(_:) method treats the block you have submitted as a user event, which means that at the end of every perform block it will make sure that all changes are processed and relevant notifications are sent.

every block submitted through the perform(_:) method gets wrapped in an autorelease pool.

performAndWait(_:) 有讨厌的副作用并且没有自动释放池,它会完全阻塞调用线程!您必须调用 processPendingChangessave() 才能使更改生效。

关于ios - 为什么我们在核心数据中使用performWait?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53776340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com