問題描述
我正在使用 dispatch_async 在后臺運行一堆項目,有時我想殺死隊列中的內容 - 這可能嗎?例如,此代碼在視圖上運行,然后用戶返回屏幕.無論返回導航如何,所有這些觸發的操作都會繼續運行.理想情況下,我想阻止這些項目運行:
I am running a bunch of items in the background using dispatch_async and sometimes I want to kill what I have in the queue - is this possible? For instance this code is run on a view, and then the user goes back a screen. All of these fired actions keep running regardless of the back navigation. Ideally I would like to kill these items from running:
dispatch_async(dispatch_get_global_queue(2, 0), ^{
for (int i=0; i<[self.manufacturers count]; i++) {
NSString *manufacturerID = [[[self.manufacturers objectAtIndex:i] ManufacturerID] stringValue];
[self doSync:manufacturerID withIndex:i setTimer:YES];
}
});
如果我創建一個隊列并命名它,然后在調用視圖的 dealloc 上釋放它,它們仍然會繼續運行.
If I create a queue and name it and then release it on the dealloc of the view this is called in they still continue to run.
推薦答案
調度隊列中沒有明確規定終止.為了做到這一點,測試一個逃生位置以確定終止是有點常見的.基本上,這將是一個信號量.
There's no explicit provision in dispatch queues for termination. In order to do this, it is somewhat common to test an escape location to determine termination. Basically, it'd be a semaphore.
NSOperationQueue
(更高級別的抽象,但仍然在底層使用 GCD 構建)確實支持取消操作.因此,例如,您可以創建一系列 NSOperations 并將它們添加到 NSOperationQueue,然后在不需要完成時將 -cancelAllOperations
消息發送到隊列.
NSOperationQueue
(a higher level abstraction, but still build using GCD underneath) does have support for canceling operations. So, for example, you can create a series of NSOperations and add them to an NSOperationQueue and then message -cancelAllOperations
to the queue when you don't need it to complete.
您選擇的很多架構將取決于其中有多少正在運行以及它們是否具有不同的觸發器.在這些實現中,NSOperation 可能是最干凈"的解決方案,因為您有一個任意隊列,您可以在該隊列中觀察要完成的操作,還可以取消未完成的操作.進一步降低黑客規模將是一個不穩定的位置,這些塊中的每一個都在一個緊密的循環內監視,以確定它們是否會過早完成.再往下是相同基本功能的全局變量.
A lot of the architecture you choose will depend on how many of these are operating and whether they have different triggers. Among the implementations, NSOperation is likely the "cleanest" solution, since you have an arbitrary queue which you can watch for operations to be finished on and you can also cancel outstanding operations. Further down the scale of hack would be a volatile location that each of these blocks watch inside of a tight loop to determine if they're going to finish prematurely. Yet further down would be a global variable for the same basic function.
最后,即使是 NSOperation 的實現也涉及到一個測試,以便在一個一致的位置退出(因為僅僅殺死一個線程可能會導致正在操作的數據或分配/重新訓練中的數據不一致).
In the end, even the implementation of NSOperation involves a test in order to exit in a consistent location (since just killing a thread might result in inconsistencies in the data being operated upon or in allocations/retrains).
這篇關于在 iOS 中殺死 dispatch_async 隊列中的項目的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!