正在从后台线程 SWIFT 更新 UI
Updating UI from background thread SWIFT
我正在使用此代码进行后台工作:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, {
// Some work in the background and updating UI too.
});
但是我正在阅读 here 我们应该使用:
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
}
更新时 UI。
我的问题是:在我使用的代码示例中,UI 在全局队列中得到更新,UI 得到更新而没有错误。我使用的方法和上面link中提到的方法有什么区别?
P.S:代码在Mac OS X 10.10
上执行
Thread Safety Summary 在
"Threading Programming Guide" 状态:
Main Thread Only Classes
The following classes must be used only from the main thread of an
application.
NSCell
and all of its descendants
NSView
and all of its descendants.
For more information, see NSView Restrictions.
绑定到主线程的唯一调度队列是
使用 dispatch_get_main_queue()
.
获得的主队列
dispatch_get_global_queue()
returns一个全局并发队列
不是主队列,因此可以执行它的工作
在辅助线程上。因此从这个队列更新 UI
可能偶然工作,但也可能导致UI更新延迟,
不工作 UI 更新或崩溃。
我正在使用此代码进行后台工作:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, {
// Some work in the background and updating UI too.
});
但是我正在阅读 here 我们应该使用:
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
}
更新时 UI。 我的问题是:在我使用的代码示例中,UI 在全局队列中得到更新,UI 得到更新而没有错误。我使用的方法和上面link中提到的方法有什么区别?
P.S:代码在Mac OS X 10.10
上执行Thread Safety Summary 在 "Threading Programming Guide" 状态:
Main Thread Only Classes
The following classes must be used only from the main thread of an application.
NSCell
and all of its descendantsNSView
and all of its descendants. For more information, see NSView Restrictions.
绑定到主线程的唯一调度队列是
使用 dispatch_get_main_queue()
.
dispatch_get_global_queue()
returns一个全局并发队列
不是主队列,因此可以执行它的工作
在辅助线程上。因此从这个队列更新 UI
可能偶然工作,但也可能导致UI更新延迟,
不工作 UI 更新或崩溃。