2017-01-11 41 views
1

我有一些任务需要异步执行。所以我正在创建一个类的dispatchqueue并执行一些任务。在swift中使用NotificationCenter停止Dispatchqueue 3

//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() 
} 

我发布了一些其他类的通知。通知正在收到。但线程没有被暂停。

这是完整的类,如果你想参考。

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) 
     } 
    } 
} 

,或者任何其他更好的方法或机制是否有这样做吗?

+0

取而代之,您可以在登录屏幕上向用户显示ActivityView,然后一旦您收到通知就停止并关闭viewController。 –

+0

停止发生在通话结束后任何程序段运行完成后。这是在https://developer.apple.com/reference/dispatch/dispatchobject/1452801-suspend中写的内容。 –

回答

1

阅读Apple`s GCD documentation,你可以看到以下内容:在通话时运行的任何块后发生

停牌。

这意味着,每个块都将被执行,已经被启动了。就在喜欢你LoginSuccessFull函数创建第二块:

anotherQueue.async { 
    print("this is the second block") 
} 

如果暂停函数调用后直,此块将不会被执行。

如果您想cancel立即在GCD的操作,您将不得不写你自己的实现。但是对于how,它始终是GCD的一个问题,因为它不仅仅是designed

另一种选择是使用NSOperationQueue,但是在那里你已经为NSOperation的子类实现了cancel逻辑。