ios - 异步下载图像而不阻塞 UI

标签 ios multithreading

我需要在不阻塞 iOS 应用程序 UI 的情况下异步下载图像。下载 image 时,“等待”UIView 必须至少显示 3 秒。我想实现一个不阻止 UI 管理的解决方案(即使在当前实现中,在图像下载正在进行时不提供任何用户操作)。

目前的解决方案是:

- main thread: dispatch_async + block to download the image (described in thread_2);
- main thread: sleep for three seconds;
- main thread: P (wait) on a semaphore S;
- main thread: read data or error message set by thread_2, then behave accordingly.


- thread_2: download the image, set data or error flag/msg according to the download result;
- thread_2: V (signal) on the semaphore S.

还有其他解决方案,例如基于 NSNotification 的解决方案,但这个解决方案似乎是尊重 3 秒延迟的最佳解决方案。

我的问题是:当主线程休眠时(或等待信号量时),UI 是否卡住?如果是,哪种解决方案最好?

你觉得第二个怎么样:

- main thread: dispatch_async + block to download the image (described in thread_2);
- main thread: dispath_async thread_3

- thread_2: as above

- thread_3: sleep three seconds, P on semaphore S;
- thread_3: read data or error message set by thread_2, prepare everything, then behave accordingly using the main_queue.

最佳答案

这是一种使用多线程和特定延迟的方式

    double delayInSeconds =3;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

    //Entering a specific thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{

        //Wait delayInSeconds and this thread will dispatch
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //Do your main thread operations here

        });
    });

关于ios - 异步下载图像而不阻塞 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23612302/

相关文章:

ios - AccountKit iOS (Facebook) 国家代码显示

ios - 尝试在我的 xcode 项目中合并 GPUImage 时添加 header 搜索路径?

c++ - 让线程每个周期调用一次init

python - 在一个线程中运行繁忙任务时所有线程都会挂起

java - 线程会让我的游戏在每台计算机上一致运行吗

ios - Cell.imageView.image 更改后不会自动加载

ios - 在 ScrollView Xcode Swift 中添加标签

iphone - 发生中断怎么办

ios - 在后台线程中使用 Couchbase

c# - 在分离线程问题中初始化存储库