DispatchWorkItem not notifying main thread

浪尽此生 提交于 2019-12-04 06:25:45

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/46483633/dispatchworkitem-not-notifying-main-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!