简体   繁体   中英

DispatchWorkItem not notifying main thread

Note: This is not duplicate question I have already seen Dispatch group - cannot notify to main thread

There is nothing answered about DispatchWorkItem

I have code like below

let dwi3 = DispatchWorkItem {
    print("start DispatchWorkItem \(Thread.isMainThread)")
    sleep(2)

    print("end DispatchWorkItem")
}
let myDq = DispatchQueue(label: "A custom dispatch queue")
dwi3.notify(queue: myDq) {
    print("notify")

}
DispatchQueue.global().async(execute: dwi3)

Which is working correctly (I can see notify on console) and not in main thread start DispatchWorkItem false

start DispatchWorkItem false

end DispatchWorkItem

notify

Now I am trying to notify to main thread using

dwi3.notify(queue: DispatchQueue.main) {
    print("notify")

}

But it never calls , I have read and found that if Thread is blocked then situation occurs. but i am already executing DisptachWorkItem in DispatchQueue.global()

Please Anyone can help me on this that what actually going on ?

在此处输入图片说明

If you are running asynchronous code in a playground then you need to enable indefinite execution, otherwise execution may end before the callbacks execute.

Add the following lines to your code in the playground:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

Once you do this, you will see that the notify executes correctly on the main queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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