简体   繁体   English

DispatchWorkItem通知主线程

[英]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 没有关于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 哪个工作正常(我可以在控制台上看到通知),而不是在主线程中启动DispatchWorkItem false

start DispatchWorkItem false 启动DispatchWorkItem false

end DispatchWorkItem 结束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. 但是它从未调用过,我已阅读并发现,如果Thread被阻止,则会发生这种情况。 but i am already executing DisptachWorkItem in DispatchQueue.global() 但是我已经在DispatchQueue.global()执行DisptachWorkItem

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. 完成此操作后,您将看到通知在主队列上正确执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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