[英]Stop Dispatchqueue using NotificationCenter in swift 3
I have some task which I want to do asynchronously.我有一些我想异步完成的任务。 So I am creating dispatchqueue in one class and doing some task.所以我在一个班级中创建 dispatchqueue 并做一些任务。
//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)
}
}
but upon some events I want to stop this, and am handling something like this.但在某些事件中,我想阻止这种情况,并且正在处理这样的事情。
func catchNotification (notification:Notification) -> Void {
//Stop the queue.
anotherQueue.suspend()
}
Am posting notification some other class.我正在其他班级发布通知。 notification is getting received.收到通知。 but thread is not getting suspended.但线程没有被挂起。
Here is the complete class if you want to refer.如果您想参考,这里是完整的课程。
LoginPresenter.swift登录Presenter.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)
}
}
}
or is any other better method or mechanism is there to do this ?或者有没有其他更好的方法或机制可以做到这一点?
Reading Apple`s GCD documentation , you could see the following:阅读Apple 的 GCD 文档,您可以看到以下内容:
The suspension occurs after completion of any blocks running at the time of the call.挂起发生在调用时运行的任何块完成之后。
This means that, every block will be executed, what has already been started.这意味着,每个块都将被执行,已经开始的。 Just create a second block in your LoginSuccessFull
function like:只需在LoginSuccessFull
函数中创建第二个块,例如:
anotherQueue.async {
print("this is the second block")
}
If you suspend straight after the function call, this block will not be executed.如果在函数调用后直接挂起,则不会执行该块。
If you would like to cancel
immediately the operations in GCD
, you will have to write you own implementation.如果您想立即cancel
GCD
的操作,则必须编写自己的实现。 But to how , it is always the one question for GCD
, because it is just not designed that way.但是如何,它始终是GCD
的一个问题,因为它不是那样设计的。
The other option would be to use NSOperationQueue
, but there you have implement right the cancel
logic for your NSOperation
subclasses.另一种选择是使用NSOperationQueue
,但您已经为您的NSOperation
子类实现了cancel
逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.