我有一些任务想异步完成。所以我在一个类中创建调度队列并执行一些任务。
//Adding Observer
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil, queue: nil, using:catchNotification).
.
//Creating Background Thread.
let anotherQueue = DispatchQueue(label: "Thread1", qos: .background)
//Asynch thread.
anotherQueue.async {
for i in 0..<50 {
print("\n 🔴",i)
sleep(1)
}
}
但在某些事件上我想阻止它,并且正在处理这样的事情。
func catchNotification (notification:Notification) -> Void {
//Stop the queue.
anotherQueue.suspend()
}
我正在向其他类(class)发布通知。收到通知。但是线程没有被挂起。
如果你想引用,这里是完整的类(class)。
LoginPresenter.swift
let anotherQueue = DispatchQueue(label: "Thread1", qos: .background)
class LoginPresenter : LoginInteractor {
func catchNotification (notification:Notification) -> Void {
//Stop the queue.
anotherQueue.suspend()
}
func LoginSuccessFull()
{
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil, queue: nil, using:catchNotification)
//Asynch thread.
anotherQueue.async {
//Synch
for i in 0..<50 {
print("\n 🔴",i)
sleep(1)
}
}
}
或者是否有任何其他更好的方法或机制可以做到这一点?
最佳答案
阅读 Apple`s GCD documentation ,您可以看到以下内容:
The suspension occurs after completion of any blocks running at the time of the call.
这意味着,每个 block 都将被执行,已经启动的 block 。只需在 LoginSuccessFull
函数中创建第二个 block ,例如:
anotherQueue.async {
print("this is the second block")
}
如果在函数调用后立即挂起,则不会执行此 block 。
如果您想立即取消
GCD
中的操作,您将必须编写自己的实现。但是要how , 它始终是 GCD
的一个问题,因为它不是 designed那样。
另一种选择是使用 NSOperationQueue
,但是您已经为您的 NSOperation
子类实现了正确的 cancel
逻辑。
关于ios - 在 swift 3 中使用 NotificationCenter 停止 Dispatchqueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41589337/