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

Why Quality of service set to background runs in main thread?

为什么我已经为后台线程指定了 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()

每当我尝试 运行 方法时,我都会在控制台中收到消息 is in main thread 但事实并非如此。我正在阅读这篇文章。

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

请参阅调度队列入门部分。

您指定了后台 queue,而不是后台 thread。当您在队列上分派任务时,GCD 会寻找一个线程来 运行 任务。

由于您使用的是同步调度,主 queue 被阻塞,主 thread 可以自由执行工作,因此您的任务在主线程上执行。

  • 在主 queue 上调度的任务 will 运行 在主 thread
  • 任务分派到另一个队列 可能 运行 在主线程或另一个 thread

这是解决方案:-

主线程的默认值总是sync,所以无论你用什么属性创建了什么队列,当它被声明时它总是在主线程运行作为 sync.

Refer this Image

第二件事主线程也可以 运行 异步,它将保证这个新任务将在当前方法完成后的某个时间执行。

第三件事是,当您使用 async 尝试相同的代码时,它将正常工作。

Refer this image

看下面的代码,自己想明白:-

func testQueue(){

    let queue = DispatchQueue(label: "com.appcoda.myqueue",qos:.background, attributes:DispatchQueue.Attributes.concurrent)

    queue.sync {   //Sync will always create main thread

        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
    }

    DispatchQueue.main.async { //Main thread can be async
        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }

    }

    if Thread.isMainThread { //default is Main thread sync
        for i in 100..<110 {
            print("Ⓜ️", i)
        }
    }
    else{
        print("is i background thread")
    }

    queue.async {   //Here your custom async thread will work
        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
    }

}

testQueue()