每天学习一个API:GCD - dispatch_async

每天学习一个API

官方定义:Submits a block for asynchronous execution on a dispatch queue and returns immediately. 将一个block对象提交到dispatch队列中去异步执行,然后马上返回。

  • 函数声明:
void dispatch_async( dispatch_queue_t queue, dispatch_block_t block);
  • 参数说明:

queue: The queue on which to submit the block. The queue is retained by the system until the block has run to completion. This parameter cannot be NULL. 系统会自动保持队列直到blcok完成为止。该参数不能为空。

一般来说,队列可分为两种类型:串行和并行。也可以分为系统队列和用户队列两种。


串行:
dispatch_get_main_queue() 主线程队列,在主线程中执行
dispatch_queue_create(DISPATCH_QUEUE_SERIAL) 自定义串行队列
并行:
dispatch_get_global_queue() 由系统维护的并行队列
dispatch_queue_create(DISPATCH_QUEUE_CONCURRENT) 自定义并发队列


  • 详细说明:

This function is the fundamental mechanism for submitting blocks to a dispatch queue. Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked. The target queue determines whether the block is invoked serially or concurrently with respect to other blocks submitted to that same queue. Independent serial queues are processed concurrently with respect to each other.

该函数为向dispatch队列中提交block对象的最基础的机制。调用这个接口后将block提交后会马上返回,并不会等待block被调用。参数queue决定block对象是被串行执行还是并行执行。不同的串行队列将被并行处理。

  • 示例展示:

    在主线程执行一个block

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"invoke in main thread.");
    });

异步执行一个block

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"invoke in another thread which is in system thread pool.");
    });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 简介 在iOS中,我们需要将非UI且耗时的任务放在主线程当中执行,同时确保在任务完成时进行回调。常用的三种实现多线...
    adduct阅读 2,985评论 0 1
  • 学习多线程,转载两篇大神的帖子,留着以后回顾!第一篇:关于iOS多线程,你看我就够了 第二篇:GCD使用经验与技巧...
    John_LS阅读 3,790评论 0 3
  • 现在iOS的多线程方案主要有以下这几种: GCD(Grand Central Dispatch):使用dispat...
    寒光冷剑阅读 5,658评论 0 2
  • 基于自 raywenderlich.com 在2015年的两篇文章 Grand Central Dispatch ...
    seedante阅读 5,185评论 0 7
  • GCD(Grand Central Dispatch) 1. 什么是GCD GCD实现了异步执行任务。开发者只需将...
    LynnXYT阅读 4,288评论 0 2