dispatch_async内部的dispatch_sync [英] dispatch_sync inside a dispatch_async

查看:95
本文介绍了dispatch_async内部的dispatch_sync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just wanted to confirm why this is needed.

我将此代码添加到KIImagePager(cocoapod)中,以加载应用程序本地的图像(默认代码从URL加载图像).

I added this code to the KIImagePager (a cocoapod) to load images that are local to the app (the default code loads images from a url).

这是我根据同事建议的工作代码:

Here's my working code based off what a coworker suggested:

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上的某些图像尚未加载).但是它们最终会加载.

I noticed that if I take out the inner dispatch_sync, it works but not in the way I want (some of the images on the image pager scrollview aren't loaded yet when I start scrolling). But they do eventually load.

我的问题是,主队列上的sync调用是否将图像返回到UI(位于主队列上)?因为它确实可以删除第二个异步文件.

My question is this, does the sync call on the main queue get the image back to the UI (which is on the main queue)? Because it does work with the second async removed.

推荐答案

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

The internal dispatch executes its code block on the main thread. This is required because all UI operations must be performed on the main thread. And you're image downloading code (context in which this snippet is executed) may be on a background thread.

外部分派在后台线程上执行其块.它给定的块是在主线程上执行的块.因此,可以安全地卸下外部块.

The external dispatch executes its block on a background thread. The block its given is the one that executes on the main thread. Thus, the external block can be safely removed.

为您使用的惯用语概述.

Hrs an outline of the idiom you're using.

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

这篇关于dispatch_async内部的dispatch_sync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆