ios - 在 swift 3 中使用 NotificationCenter 停止 Dispatchqueue

标签 ios swift3 dispatch-async

我有一些任务想异步完成。所以我在一个类中创建调度队列并执行一些任务。

//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/

相关文章:

iOS Build 在 Xcode 中运行良好,但 Appcenter.ms 失败

ios - 在 nib 文件中按下时如何禁用 UIButton 突出显示?

iphone - 如何在应用程序中提供多语言常见问题解答?

ios - 没有使用 Objective-c 分配给属性 swift 3 的 setter 方法

ios - 对象-C : dispatch_async crashes without NSLog

ios - Xcode 4.6 和 Xcode 5 安装在一起

arrays - Swift 数组初始化 : data[section][row]

ios - 带有 xml 解析器的dispatch_async 不工作

Swift - 在线程中执行SegueWithIdentifier

google-maps - -canOpenURL : failed for URL: "comgooglemaps://" - error: "The operation couldn’ t be completed