Reputation: 17715
I have an iPhone app where based on some parameters an image gets recreated. Since this image recreation can take some time, I use a separate thread to create the image.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
// costly drawing
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
self.image = newImage;
});
});
The parameters affecting the recreation of this image can vary faster than the image can get recreated, so I'd like to "pause" recreation when needed and only perform one such dispatch_async call at a time.
Then as more requests to recreate the image arrive, only remember the last one (with the most up to date parameters), and as soon as the image recreation finished start one for those parameters.
It doesn't matter that all the other calls are never done, the image would be overwritten anyway.
What's the best way to achieve this?
Upvotes: 2
Views: 150
Reputation: 46713
You may want to consider using NSOperationQueue
since you can cancel existing queue items every time a new one is added.
Using dispatch_async
will run whatever you place in the block until completion (unless you suspend the entire queue) so there's not a great way of stopping prior queue items without setting some sort of a cancellation flag (in which case, they are just short-circuited but the block is still run to completion).
NSOperationQueue
is built on top of GCD so it provides the same backgrounding capabilities, it just gives you more control over the queue, which is what you need in this case. It can also be run concurrently on multiple threads, but you shouldn't need that.
Upvotes: 2