swift - 在 Swift 中使用 DispatchQueue 时出现时间差异

标签 swift asynchronous queue grand-central-dispatch swift-playground

我有一个必须每半秒执行一次的代码,并且我正在使用 Xcode Playground。我用过这个top answer并得到这样的代码:

for (index, item) in array.enumerated() {
            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(index), execute: {
                print("\(index) - \(df.string(from: Date()))"
                //play sound every second
            })
        }

这段代码每秒执行一次(我知道我必须将其除以 2 才能得到半秒,但想查看结果)。我使用 DateFormatter 来计算时间,因为我无法弄清楚为什么声音播放不均匀。

let df = DateFormatter()
df.dateFormat = "ss.SSSS"

结果是它并不是每1秒触发一次。

0 - 17.4800
1 - 18.5770 // even though it's not called exactly after 1s it's acceptable
2 - 19.6750
3 - 20.7770
4 - 21.8780
5 - 22.9760
6 - 24.0710
7 - 25.1690
8 - 26.2720
9 - 27.3640
10 - 28.4760 
11 - 28.7580 //0.3s of difference
12 - 30.4800
13 - 30.5060 // 0.1s of difference
14 - 32.4800
15 - 32.5030 // less than 0.1s of difference

最佳答案

这里你异步执行你的Print语句,这样你就不会在半秒(或一秒)后得到你的打印数据。如果你同步执行它,那么你会以1秒的间隔得到你的打印数据。要了解有关调度队列的更多信息,请关注 this链接。如果您有任何问题,请告诉我。

关于swift - 在 Swift 中使用 DispatchQueue 时出现时间差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347450/

相关文章:

ios - 如何快速将数组连接到另一个 View Controller ?

swift - 初始化器 'init(_:)' 要求 '' 符合 'StringProtocol' SwiftUI Picker with Firebase

python - webdriver 和 asyncio

node.js:从 url 下载许多图像:由于同时下载太多而超时

java - 在单独的 JavaFX 线程中排队打印作业

c++ - enqueue() 方法向队列 : how to implement in C++? 添加一个元素

java - 垃圾收集行为

swift - 亚马逊签名创建

macos - 使用 Swift 中的 AudioToolbox 访问 OS X 主音量

c# - 为什么 async await 会抛出 NullReferenceException?