How to stop the execution of tasks in a dispatch queue? How to stop the execution of tasks in a dispatch queue? multithreading multithreading

How to stop the execution of tasks in a dispatch queue?


There is no way to empty pending tasks from a dispatch queue without implementing non-trivial logic yourself as of iOS 9 / OS X 10.11.

If you have a need to cancel a dispatch queue, you might be better off using NSOperationQueue which offers this and more. For example, here's how you "cancel" a queue:

NSOperationQueue* queue = [NSOperationQueue new];queue.maxConcurrentOperationCount = 1; // make it a serial queue...[queue addOperationWithBlock:...]; // add operations to it...// Cleanup logic. At this point _do not_ add more operations to the queuequeue.suspended = YES; // halts execution of the queue[queue cancelAllOperations]; // notify all pending operations to terminatequeue.suspended = NO; // let it go.queue=nil; // discard object


If you're using Swift the DispatchWorkItem class allows works units to be cancelled individually.

Work items allow you to configure properties of individual units of work directly. They also allow you to address individual work units for the purposes of waiting for their completion, getting notified about their completion, and/or canceling them. ( available for use in iOS 8.0+macOS 10.10+ ).

DispatchWorkItem encapsulates work that can be performed. A work item can be dispatched onto a DispatchQueue and within a DispatchGroup. A DispatchWorkItem can also be set as a DispatchSource event, registration, or cancel handler.

https://developer.apple.com/reference/dispatch/dispatchworkitem


This is a pretty common question, and one I've answered before:

Suspending GCD query problem

The short answer is that GCD doesn't have a cancellation API; you have to implement your cancellation code yourself. In my answer, above, I show basically how that can be done.