dispatch_get_global_queue vs dispatch_get_main_queue [英] dispatch_get_global_queue vs dispatch_get_main_queue

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

问题描述

开始了解核心数据和dispatch_async。有一段代码可以从数据集中获取图像的url并将其设置为核心数据模型,如下所示

Starting to learn about core data and dispatch_async. There is a block of code to get url of image from set of data and set it to model of core data like below

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                NSString *urlString = [[[photoDictionary valueForKey:@"images"] objectAtIndex:0] valueForKey:@"url"];
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [photoModel setValue:imageData forKey:@"photoImageData"];

有人可以向我解释为什么我们使用 dispatch_get_global_queue 作为外部dispatch_async和 dispatch_get_main_queue 用于内部dispatch_async。

Can somebody explain to me why we use dispatch_get_global_queue for the outer dispatch_async and dispatch_get_main_queue for inner dispatch_async.

推荐答案

dispatch_get_global_queue 为您提供一个后台队列,您可以在其上调度异步运行的后台任务(即获胜)阻止你的用户界面。如果您最终向全局队列提交多个块,则这些作业可以同时运行。如果您有多个代码块要提交到后台必须在后台运行的后台队列(通常不需要),您可以创建自己的串行后台队列并调度到该队列,但是如果并发后台操作是可以接受,然后利用 dispatch_get_global_queue 方便/高效。

The dispatch_get_global_queue gets you a background queue upon which you can dispatch background tasks that are run asynchronously (i.e. won't block your user interface). And if you end up submitting multiple blocks to the global queues, these jobs can operate concurrently. If you have multiple blocks of code that you want to submit to a background queue that you must have run sequentially in the background (not often needed), you could create your own serial background queue and dispatch to that, but if concurrent background operations are acceptable, then availing yourself of dispatch_get_global_queue is convenient/efficient.

请注意,你不是允许在后台队列中执行用户界面更新,因此 dispatch_async dispatch_get_main_queue 允许后台队列调度用户一旦主队列可用,接口就会更新回主队列。

Be aware, though, that you're not allowed to perform user interface updates in the background queue, so the dispatch_async to the dispatch_get_main_queue lets that background queue dispatch the user interface updates back to the main queue, once the main queue is available.

这是一种非常常见的编程模式:提交在后台运行的东西,当需要执行用户更新时,将更新发送回主队列。

This is a very common programming pattern: Submit something to run in the background and when it needs to perform user updates, dispatch the update back to the main queue.

有关详细信息,请参阅并发编程指南

For more information, refer to the Concurrency Programming Guide.

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

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