dispatch_async中的dispatch_sync

时间:2013-06-08 19:12:15

标签: ios objective-c multithreading

我只想确认为什么需要这样做。

我将此代码添加到KIImagePager(一个cocoapod)以加载应用程序本地的图像(默认代码从网址加载图像)。

这是我的工作代码基于同事的建议:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [imageView setImage:[UIImage imageNamed:[aImageUrls objectAtIndex:i]]];;
                });
            });

我注意到,如果我取出内部dispatch_sync,它可以工作但不是我想要的方式(当我开始滚动时,图像寻呼机scrollview上的一些图像尚未加载)。但他们最终会加载。

我的问题是,主队列上的同步调用是否将图像返回到UI(位于主队列中)?因为它确实可以在删除第二个异步时使用。

2 个答案:

答案 0 :(得分:9)

内部调度在主线程上执行其代码块。这是必需的,因为必须在主线程上执行所有UI操作。并且您的图像下载代码(执行此代码段的上下文)可能位于后台线程上。

外部调度在后台线程上执行其块。它给定的块是在主线程上执行的块。因此,可以安全地移除外部块。

描述你正在使用的习语。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    // do blocking work here outside the main thread. 
    // ...
    // call back with result to update UI on main thread
    //
    // what is dispatch_sync? Sync will cause the calling thread to wait
    // until the bloc is executed. It is not usually needed unless the background
    // background thread wants to wait for a side effect from the main thread block
    dispatch_sync(dispatch_get_main_queue(), ^{
        // always update UI on main thread
    });
});

答案 1 :(得分:2)

您应该只使用主线程上的UI对象。如果不这样做,您将遇到一些问题。如您所见,第一个是UI对象在更新时会延迟。第二个是如果您尝试同时从多个线程更改UI对象,应用程序可能会崩溃。您应该只在主线程上使用UI对象。