官方定義: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.");
});