DispatchWorkItem通知主线程 [英] DispatchWorkItem not notifying main thread
问题描述
注意:这不是重复的问题,我已经见过调度组-无法通知主线程
Note: This is not duplicate question I have already seen Dispatch group - cannot notify to main thread
关于 DispatchWorkItem
我有如下代码
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)
哪个工作正常(我可以在控制台上看到通知),而不是在主线程中启动DispatchWorkItem false
Which is working correctly (I can see notify on console) and not in main thread start DispatchWorkItem false
启动DispatchWorkItem为假
start DispatchWorkItem false
结束DispatchWorkItem
end DispatchWorkItem
通知
现在我正尝试使用通知主线程
Now I am trying to notify to main thread using
dwi3.notify(queue: DispatchQueue.main) {
print("notify")
}
但是它从未调用过,我已经阅读并发现,如果Thread被阻塞,则会发生这种情况.但是我已经在DispatchQueue.global()
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.
这篇关于DispatchWorkItem通知主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!