iOS多執行緒的初步研究(九)— dispatch源
dispatch源的使用基本為以下步驟:
1. dispatch_source_t source = dispatch_source_create(dispatch_source_type, handler, mask, dispatch_queue);
2. dispatch_source_set_event_handler(source, ^{ //設定響應dispatch源事件的block,在dispatch源指定的佇列上執行
//可以通過dispatch_source_get_data(source)來得到dispatch源資料
});
3. dispatch_resume(source); //dispatch源建立後處於suspend狀態,所以需要啟動dispatch源
4. dispatch_source_merge_data(source, value);
是不是很簡單?而且完全不必編寫同步的程式碼。比如網路請求資料的模式,就可以這樣來寫:
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_global_queue(0, 0));
dispatch_source_set_event_handler(source, ^{
dispatch_sync(dispatch_get_main_queue(), ^{
//更新UI
});
});
dispatch_resume(source);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//網路請求
dispatch_source_merge_data(source, 1); //通知佇列
});
dispatch源還支援其它一些系統源,包括定時器、監控檔案的讀寫、監控檔案系統、監控訊號或程序等,基本上呼叫的方式原理和上面相同,只是有可能是系統自動觸發事件。比如dispatch定時器:
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 10*NSEC_PER_SEC, 1*NSEC_PER_SEC); //每10秒觸發timer,誤差1秒
dispatch_source_set_event_handler(timer, ^{
//定時處理
});
dispatch_resume(timer);
最後,dispatch源的其它一些函式大致羅列如下:
uintptr_t dispatch_source_get_handle(dispatch_source_t source); //得到dispatch源建立,即呼叫dispatch_source_create的第二個引數
unsignedlong dispatch_source_get_mask(dispatch_source_t source); //得到dispatch源建立,即呼叫dispatch_source_create的第三個引數
void dispatch_source_cancel(dispatch_source_t source); //取消dispatch源的事件處理--即不再呼叫block。如果呼叫dispatch_suspend只是暫停dispatch源。
long dispatch_source_testcancel(dispatch_source_t source); //檢測是否dispatch源被取消,如果返回非0值則表明dispatch源已經被取消
void dispatch_source_set_cancel_handler(dispatch_source_t source, dispatch_block_t cancel_handler); //dispatch源取消時呼叫的block,一般用於關閉檔案或socket等,釋放相關資源
void dispatch_source_set_registration_handler(dispatch_source_t source, dispatch_block_t registration_handler); //可用於設定dispatch源啟動時呼叫block,呼叫完成後即釋放這個block。也可在dispatch源運行當中隨時呼叫這個函式。