Prashant Tukadiya
Prashant Tukadiya

Reputation: 16436

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 ?

enter image description here

Upvotes: 0

Views: 589

Answers (1)

Paulw11
Paulw11

Reputation: 114836

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.

Upvotes: 2

Related Questions