了解 dispatch_async [英] Understanding dispatch_async

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

问题描述

我对这段代码有疑问

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData* data = [NSData dataWithContentsOfURL: 
      kLatestKivaLoansURL];
    [self performSelectorOnMainThread:@selector(fetchedData:) 
      withObject:data waitUntilDone:YES];
});

这段代码的第一个参数是

The first parameter of this code is

dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 

我们是否要求这段代码在全局队列上执行串行任务,其定义本身是它返回给定优先级的全局并发队列?

Are we asking this code to perform serial tasks on global queue whose definition itself is that it returns global concurrent queue of a given priority level?

在主队列上使用 dispatch_get_global_queue 有什么优势?

What is advantage of using dispatch_get_global_queue over the main queue?

我很困惑.请您帮助我更好地理解这一点.

I am confused. Could you please help me to understand this better.

推荐答案

使用默认队列而不是主队列的主要原因是在后台运行任务.

The main reason you use the default queue over the main queue is to run tasks in the background.

例如,如果我正在从 Internet 下载文件并且我想更新用户的下载进度,我将在优先级默认队列中运行下载并异步更新主队列中的 UI.

For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

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

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