简体   繁体   English

如何在GCD中的下一个块之前取消上一个块? [重复]

[英]how to cancel previous block by the coming block in GCD? [duplicate]

Possible Duplicate: 可能重复:
How do I kill/suspend/close an asyncronous block in GCD? 如何杀死/暂停/关闭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. 我使用UIScrollView来让用户滚动所有图像,因为该图像不是标准的jpg或png,因此加载需要花费时间。 I use GCD to load asynchronously, when finished dispatch to main queue to display. 我使用GCD异步加载,完成分配到主队列后显示。 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. 但是,如果滚动得如此之快,以至于该方法可能在要显示的第一个加载图像之前被调用几次。然后,当您停止时,当前imageView将快速显示先前的几幅图像,然后最后显示当前图像。 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. 提前致谢。

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. 您正在使用类方法加载图像,但是同时从各个线程(通过块)调用它们,因此我希望您为此设计了Reader。 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. 无论如何,我建议您做的是创建一个可变集,并且每当您向Reader发送消息以加载图像时,首先将名称添加到该集中。 When it returns, then delete the name but on the main thread (both add and delete done on mainQueue or main thread. 返回时,删除名称,但在主线程上删除(在mainQueue或主线程上添加和删除完成)。

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. 现在,当您要停止处理一个或所有图像时,请向Reader添加一个新的“ cancelLoad”方法,并向其发送一个您希望其停止处理的名称的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM