每天学习一个API:GCD - dispatch_async

97652-f57468063bee5568.jpeg
每天学习一个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.");
    });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值