繁体   English   中英

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

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

尝试为您的后台任务添加延迟 - 看看会发生什么

DispatchQueue.global(qos: .background).async {
    DispatchQueue.main.async {
        print("This is run on the main queue")
    }

    longRunningFunction
    print("This is run on the background queue")
}


func longRunningFunction() {
    sleep(1)
}

现在您将看到您期望的输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM