ios - 后台线程在主线程 ios swift 之前执行
问题描述
我想推送一个视图控制器并希望休息任务在后台工作而不会冻结 UI。但我的 UI 冻结或后台线程之前执行。附上我工作的一个小例子。
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
print("This is run on the main queue, after the previous code in outer block")
}
print("This is run on the background queue")
}
结果:
This is run on the background queue
This is run on the main queue, after the previous code in outer block
主队列应该比后台线程先执行。
解决方案
您的代码基本上是这样执行的:
// 1. Send this code off to the global queue to be processed async
DispatchQueue.global(qos: .background).async {
// 3. You're here once the global queue decides it's ready to run this code
// 4. Send this code off to the main queue to be processed async
DispatchQueue.main.async {
// 6. You're here once the main queue decides it's ready to run this code
print("This is run on the main queue, after the previous code in outer block")
}
// 5. This is now printed
print("This is run on the background queue")
}
// 2. whatever happens here
您的代码像这样运行的原因是您正在异步调度所有内容。这意味着您所做的只是传递闭包,以便稍后由目标队列执行,或者在它准备好时执行。通过使用 async 你告诉队列你不想等待这个。
如果您希望您的主队列位立即运行,您可以使用DispatchQueue.main.sync
。这将阻止您所在的上下文的执行(在这种情况下是async
您传递给全局队列的闭包),直到您正在运行的闭包sync
完成。
我通常建议避免sync
,除非你真的需要它,因为让队列等待自己并永远被锁定(死锁)太容易了。
推荐阅读
- c# - 我可以将原始字节发送到 MIDI 设备吗?
- python - 无法在 Google App Engine 柔性环境 (Python) 上运行 cron 作业
- python - 如何使用循环运行查询以使用 python 在 mongodb 中获取每日数据
- javascript - 如何使用 getUserMedia() 截屏;javascript中的API
- php - 如何解决未定义的路线
- vb.net - VB Webclient“底层连接已关闭”
- html - 模糊效果不适用于“悬停”元素上方的元素
- ios - CollectionView didSelectItemAt 没有被调用
- flutter - 在 Flutter 中创建日文假名 EditableText
- laravel - 在 Laravel 6/7 中删除相关模型