-1

Possible Duplicate:
How do I kill/suspend/close an asyncronous block in GCD?

I am working on an app that does image processing and displays the resulting image. Im using UIScrollView to let user scroll all images, because the image is not a standard jpg or png, it takes time to load. I use GCD to load asynchronously, when finished dispatch to main queue to display. the snippet is as follows:

- (void)loadImage:(NSString *)name
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *image = [Reader loadImage:name];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self displayImage:image];
        });
    });
}

This works well in most cases. But when you scroll so fast that the method may be called several times before the first loaded image to be displayed.Then when you stop,the current imageView will display several previous images quickly, then the current image is displayed at last. which is easy to crash because of memory problem.

I wonder whether there is a way to notify the queue to cancel the previous ones if there is a new block in the queue(which means the method is called again before the previous block is finished)? or any other better suggestions?

Thanks in advance.

Community
  • 1
  • 1
chancyWu
  • 14,073
  • 11
  • 62
  • 81

1 Answers1

1

You are using class methods to load images, but calling them from various threads concurrently (via the blocks) so I hope you have designed Reader for that. In any case, what I suggest you do is create a mutable set and each time you message Reader to load an image, first add the name to the set. When it returns, then delete the name but on the main thread (both add and delete done on mainQueue or main thread.

Now, when you want to stop processing one or all images, add a new 'cancelLoad' method to Reader, and send it a list of the names you want it to stop processing.

David H
  • 40,852
  • 12
  • 92
  • 138