swift - 当 workItem 在后台线程上完成时,如何通知主线程?

标签 swift

我必须在主线程上执行类似 NSProgressIndicator.stopAnimation 的操作。但是我想在分配给后台线程的 workItem 结束时执行此操作。

NSProgressIndicator.startAnimation(self)

let workItem = DispatchWorkItem {
     //
     // Some tasks
     //

     // This doesn't work, how do I call it on main thread?
     NSProgressIndicator.stopAnimation(self)
}

DispatchQueue.global(qos: .background).async(execute: workItem)

最佳答案

使用 DispatchQueue.main.async 就像在主队列上运行任何代码一样。

let workItem = DispatchWorkItem {
     //
     // Some tasks
     //

     DispatchQueue.main.async {
         NSProgressIndicator.stopAnimation(self)
     }
}

关于swift - 当 workItem 在后台线程上完成时,如何通知主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493039/

相关文章:

ios - 模式转换后未调用 IBAction

iOS swift : order of code execution/asynchronous execution

swift - 如何在命令行上使用和运行 Swift 2.3

ios - 更改特定页面 UiPageViewController

ios - 如何指定我想要在 GraphQLQuery 中获取的字段

swift - 使用 getRectsBeingDrawn : with Swift

swift - 重新加载表格 View 而不隐藏键盘

ios - 为什么这个值不在我的 ViewController 之间传递?

ios - Swift:使用协议(protocol)扩展导致 "unrecognized selector sent to instance"

swift - Swift 自动关闭延迟是如何工作的?