后台线程在主线程之前执行 ios swift

Pat*_*ush 0 xcode multithreading ios swift ios13

我想推送一个视图控制器,并希望其余任务在后台工作而不冻结 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")
    }
Run Code Online (Sandbox Code Playgroud)

结果:

This is run on the background queue
This is run on the main queue, after the previous code in outer block
Run Code Online (Sandbox Code Playgroud)

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

don*_*als 5

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

// 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
Run Code Online (Sandbox Code Playgroud)

您的代码像这样运行的原因是您正在异步分派所有内容。这意味着您所做的就是将闭包传递给目标队列,以便稍后或在准备就绪时由目标队列执行。通过使用异步,你告诉队列你不想等待这个。

如果您希望主队列位立即运行,您可以使用DispatchQueue.main.sync。这将阻止您所在上下文的执行(在本例中async是您传递给全局队列的闭包),直到您正在运行的闭包sync完成。

我通常建议避免,sync除非您确实需要它,因为让队列等待自身并永远锁定(死锁)太容易了。