[英]Why calling `DispatchQueue.main.sync` asynchronously from concurrent queue succeeds but synchronously fails?
[英]Performing UI updates on main thread synchronously from a concurrent queue
据我了解,GCD UI操作应始终在主线程/主队列上异步执行。 但是以下代码似乎也可以正常工作。 有人可以解释为什么吗? 我正在将2个块同步传递给dispatch_async。 一个块下载图像,另一个块将其显示在视图上。
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
__block UIImage *image = nil;
dispatch_sync(concurrentQueue, ^{
/* Download the image here */
});
dispatch_sync(dispatch_get_main_queue(), ^{
/* Show the image to the user here on the main queue */
});
});
队列很重要(必须是主队列),但是gcd调用是同步还是异步无关紧要-这只会影响围绕gcd调用的其余代码的计时方式。 一旦块在队列上运行,调度的方式就无关紧要了。
同步分派可以简化您的代码(因为它只有在执行该块后才会返回),但是如果您最终等待完成,则确实存在被锁定的风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.