![](/img/trans.png)
[英]Difference between dispatch_async and dispatch_sync on serial queue?
[英]dispatch_sync inside a dispatch_async
我只是想确认为什么需要它。
我将此代码添加到KIImagePager(一个cocoapod)以加载应用程序本地的图像(默认代码从URL加载图像)。
这是我的工作代码基于同事的建议:
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(位于主队列中)? 因为它确实与删除的第二个异步一起工作。
内部调度在主线程上执行其代码块。 这是必需的,因为必须在主线程上执行所有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
});
});
您应该只使用主线程上的UI对象。 如果不这样做,您将遇到一些问题。 如您所见,第一个是UI对象在更新时会延迟。 第二个是如果您尝试同时从多个线程更改UI对象,应用程序可能会崩溃。 您应该只使用主线程上的UI对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.