2017-01-11 44 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邏輯。