【问题标题】:How to showing line one by one in async code?如何在异步代码中逐行显示?
【发布时间】:2018-05-17 02:46:42
【问题描述】:

我想用 async 做 for 循环代码。为了模拟异步,我添加了一些延迟。

import Cocoa

class ViewController: NSViewController {
    private let semaphore = DispatchSemaphore(value: 0)
    private let concurrentQueue = DispatchQueue.global()

    override func viewDidLoad() {
        super.viewDidLoad()

        for i in 1...10 {
            if run(i) {
                break
            }
        }
    }

    func run(_ i:Int) -> Bool{
        let seed = arc4random()
        let isSuccess = seed % 5 == 1
        let delayInSeconds = Int(seed % 3)

        concurrentQueue.asyncAfter(wallDeadline: .now() + .seconds(delayInSeconds)) {
            DispatchQueue.main.async {
                self.textView.string += "\(i)\t\(seed)\n"
            }

            self.semaphore.signal()
        }

        semaphore.wait()

        return isSuccess
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBOutlet var textView: NSTextView!
}

问题是,当代码运行时,所有行都被同时添加了。我要一一添加。有什么想法吗?

【问题讨论】:

    标签: swift macos for-loop asynchronous appkit


    【解决方案1】:

    问题解决了。更新 UI 部分不起作用的原因是因为 func run() 正在主线程上运行,而 semaphore.wait() 总是阻止它。所以为了解决这个问题,只是将它添加到另一个线程。

    override func viewDidLoad() {
        super.viewDidLoad()
    
        concurrentQueue.async {
            for i in 1...10 {
                if self.run(i) {
                    break
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 2016-12-08
      • 2013-01-02
      • 1970-01-01
      相关资源
      最近更新 更多