-1

可能重复:
如何在 GCD 中终止/暂停/关闭异步块?

我正在开发一个进行图像处理并显示结果图像的应用程序。我使用 UIScrollView 让用户滚动所有图像,因为图像不是标准的 jpg 或 png,加载需要时间。我使用 GCD 异步加载,当完成调度到主队列以显示时。片段如下:

- (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];
        });
    });
}

这在大多数情况下都很有效。但是当你滚动的太快,可能会在第一个加载的图像显示之前调用该方法多次。然后当你停止时,当前的imageView会快速显示之前的几个图像,然后最后显示当前的图像。由于内存问题很容易崩溃。

我想知道如果队列中有一个新块(这意味着在前一个块完成之前再次调用该方法),是否有办法通知队列取消以前的队列?或任何其他更好的建议?

提前致谢。

4

1 回答 1

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.

于 2012-09-13T12:29:38.867 回答