每天學習一個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閱讀 402評論 0 1
  • 學習多線程,轉載兩篇大神的帖子,留著以后回顧!第一篇:關于iOS多線程,你看我就夠了 第二篇:GCD使用經驗與技巧...
    John_LS閱讀 638評論 0 3
  • 現在iOS的多線程方案主要有以下這幾種: GCD(Grand Central Dispatch):使用dispat...
    寒光冷劍閱讀 1,693評論 0 2
  • 基于自 raywenderlich.com 在2015年的兩篇文章 Grand Central Dispatch ...
    seedante閱讀 1,405評論 0 7
  • GCD(Grand Central Dispatch) 1. 什么是GCD GCD實現了異步執行任務。開發者只需將...
    LynnXYT閱讀 854評論 0 2