-1

假设我有几个数据库写入闭包,我想在单个线程上执行它们,但不是作为批处理 - 我需要在每次写入后更新 UI。

串行队列如:

DispatchQueue.global(qos: .background).async {}

或者

DispatchQueue(label: "hello world").async {}

在他们想要运行的任何线程中运行,尽管是串行的。

我怎样才能有一个只在一个后台线程上运行的队列?

4

1 回答 1

3

正如其他人指出的那样,代码运行在哪个线程上并不重要。像这样的性能问题通常取决于简单地按顺序运行任务,一次一个,因此它们不会与资源重叠或冲突。

最简单的解决方案是创建一个顺序队列。(在 Safari 中输入,因此值得您为此付出的每一分钱)

let queue = DispatchQueue(label: "db.update", qos: .utility, attributes: [], autoreleaseFrequency: .inherit, target: nil)

var progress: Int = 0

queue.async {
    // Dome some work, then update the UI
    progress = 2
    DispatchQueue.main.async(execute: {
        // label.text = "did something"
        // progress.doubleValue = Double(progressCounter)
    })
}

queue.async {
    // Do some more work
    progress += 1
    // This won't execute until the first block has finished
}

queue.async {
    // Even more work
    progress += 1
}

queue.async {
    // And so on...
    progress += 1   // This block might, for example, notify the system that everything has finished
    print("progress is finally \(progress)")
}

关键是每个块都是按顺序执行的(因为队列不是“并发的”),直到前一个块完成后才会开始下一个块。每个块可能会或可能不会在同一个线程上执行,但这无关紧要。

一个块的结果/进度可以很容易地通过闭包变量传递给下一个块。

于 2019-07-11T02:17:54.360 回答