为什么设置为后台的服务质量在主线程中运行?

0 multithreading grand-central-dispatch ios swift

为什么下面的代码在主线程中运行,虽然我已经为后台线程指定了qos?

func testQueue(){

    let queue = DispatchQueue(label: "com.appcoda.myqueue",qos:.background)
    queue.sync {

        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
        for i in 100..<110 {
            print("??", i)
        }
    }
}

testQueue()
Run Code Online (Sandbox Code Playgroud)

每当我尝试运行该方法时,我会在控制台中获取msg is in main thread,但不应该是这种情况.我正在阅读本文.

http://www.appcoda.com/grand-central-dispatch/

请参阅"调度队列入门"部分.

Pau*_*w11 5

您已指定后台队列,而不是后台线程.在队列上调度任务时,GCD会查找要运行任务的线程.

由于您正在使用同步分派,因此主队列被阻止,主线程可以自由执行,因此您的任务在主线程上执行.

  • 在主队列 上调度的任务在主线程上运行
  • 在另一个队列 上调度的任务可以在主线程或另一个线程上运行