迅速等待异步任务 [英] Swift wait for async task
本文介绍了迅速等待异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在后台线程中,我们有:
In a background thread we have:
defer {
cleanup()
}
loadData()
if error {
return
}
processData()
DispatchQueue.main.asyncAfter(deadline: delay) { //Delay = now + 0-2 seconds
updateUI()
}
问题是我们要确保延迟 cleanUp()
代码在 updateUI()
之后运行.就目前而言,这不会发生,因为 updateUI()
运行异步.
The problem is we want to ensure that the defer cleanUp()
code runs after updateUI()
. And as it stands this won't happen as updateUI()
runs async.
我的想法是在该延迟时间内睡眠/阻止,而不是异步运行.完成 updateUI()
后,这将延迟运行 cleanUp()
.
My thought was to sleep/block for that delay period instead of running asynchronously. This would have the defer cleanUp()
run once updateUI()
is done.
您该怎么做?还是有更好的方法?
How can you do this? Or is there a better way?
推荐答案
意识到我可以更改代码的结构:
Realized I could just change the structure of the code:
loadData()
if error {
log.error("Error")
} else {
processData()
}
DispatchQueue.main.asyncAfter(deadline: delay) { //Delay = now + 0-2 seconds
updateUI()
cleanup()
}
这篇关于迅速等待异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文