迅速:异步任务+完成 [英] swift: async task + completion
本文介绍了迅速:异步任务+完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很快就对异步任务感到困惑.我想做的就是这样...
I got quite a lot of confusion on async tasks in swift. What i want to do is something like this...
func buttonPressed(button: UIButton) {
// display an "animation" tell the user that it is calculating (do not want to freeze the screen
// do some calculations (take very long time) at the background
// the calculations result are needed to update the UI
}
我试图做这样的事情:
func buttonPressed(button: UIButton) {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) { () -> Void in
// display the animation of "updating"
// do the math here
dispatch_async(dispatch_get_main_queue(), {
// update the UI
}
}
}
但是,我发现UI的更新没有等待我的计算完成.我对异步队列的使用感到很困惑.有人帮忙吗?谢谢.
However, I found that the UI is updated without waiting my calculation to be completed. I am quite confused on the use of async queue. Anyone help? Thanks.
推荐答案
您需要一个带有异步完成处理程序的函数.
You need a function with a asynchronous completion handler.
在计算结束时调用completion()
func doLongCalculation(completion: () -> ())
{
// do something which takes a long time
completion()
}
在buttonPressed
函数中,将计算函数分派到后台线程上,并在完成后返回主线程以更新UI
In the buttonPressed
function dispatch the calculate function on a background thread and after completion back to the main thread to update the UI
func buttonPressed(button: UIButton) {
// display the animation of "updating"
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.doLongCalculation {
dispatch_async(dispatch_get_main_queue()) {
// update the UI
print("completed")
}
}
}
}
这篇关于迅速:异步任务+完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文