保留中のすべての操作をキャンセルするために使用できますNSOperationQueue
が、それでも既存の操作はキャンセルされません。既存の操作をキャンセルするには、まだ何かを実装する必要があります...これは、キュー内の操作を早期に中止するためにも機能します。
私のユースケースに、より適した他の利点がない限り、通常はストレート GCD を好みますNSOperationQueue
。
また、ロードに外部キャンセル メカニズムがある場合は、保留中の I/O 操作をキャンセルする必要があります。
操作が独立している場合は、他のリクエストがキャンセルされているときに新しいリクエストを同時に実行できるようにするため、同時キューを検討してください。
また、それらがすべて I/O である場合はdispatch_io
、スレッドをブロックする代わりに使用できるかどうかを検討してください。モンクが言うように、「あなたは後で私に感謝します.
次のようなことを考えてみましょう:
- (void)userRequestedNewSearch:(SearchInfo*)searchInfo {
// Assign this operation a new token, that uniquely identifies this operation.
uint32_t token = [self nextOperationToken];
// If your "loading" API has an external abort mechanism, you want to keep
// track of the in-flight I/O so any existing I/O operations can be canceled
// before dispatching new work.
dispatch_async(myQueue, ^{
// Try to load your data in small pieces, so you can exit as early as
// possible. If you have to do a monolithic load, that's OK, but this
// block will not exit until that stops.
while (! loadIsComplete) {
if ([self currentToken] != token) return;
// Load some data, set loadIsComplete when loading completes
}
dispatch_async(dispatch_get_main_queue(), ^{
// One last check before updating the UI...
if ([self currentToken] != token) return;
// Do your UI update operations
});
});
}
最後に送信された操作以外の操作は早期に中止されます。使用したNSOperationQueue
場合は呼び出すことができますcancelAllOperations
が、現在実行中のものを早期に中止するには、同様のメカニズムが必要です。