首页 > 解决方案 > 后台线程在主线程 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

主队列应该比后台线程先执行。

标签: iosswiftxcodemultithreadingios13

解决方案


您的代码基本上是这样执行的:

// 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,除非你真的需要它,因为让队列等待自己并永远被锁定(死锁)太容易了。


推荐阅读