Dispatch 方法简介

后台执行

dispatch_async(dispatch_get_global_queue(0, 0), ^{ 

    //后台程执行 something; 

}); 

主线程执行

dispatch_async(dispatch_get_main_queue(), ^{

    // 主线程执行something;

});

 

一次性执行

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{ 

    // 主要用于单例

});

 

延迟执行

double delayInSeconds = 2.0;

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PE R_SEC);

dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 

    // code to be executed on the main queue after delay

});

 

创建自定义的线程

dispatch_queue_t myQueue = dispatch_queue_create("com.cnblogs.yybz", NULL); dispatch_async(myQueue, ^{

    // your code

});

 

设置自定义线程的优先级

 

dispatch_queue_t myQueue = dispatch_queue_create("com.cnblogs.yybz", NULL); 

dispatch_queue_t globalHightQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); 

dispatch_set_target_queue(myQueue, globalHighQueue);

 

 

dispatch_group_async(group, queue, ^{ 

    // code

}); 



dispatch_group_wait(group, DISPATCH_TIME_FOREVER); //超时参数 

dispatch_group_notify(group, queue, ^{

    // code

});



dispatch_group_enter(group);

dispatch_async(queue, ^{

    //code

    dispatch_group_leave(group);

});

 

并行同步执行

/**

@parameter iterations 迭代器数量

@parameter queue 提交任务的队列

@parameter (^block)(size_t) 任务Block,size_t 为迭代器下标

**/

dispatch_apply(size_t iterations, dispatch_queue_t queue, void (^block)(size_t));

 

队列挂起与恢复

dispatch_suspend(queue); 

dispatch_resume(myQueue);

 

信号量

dispatch_semaphore_create; //创建一个semaphore

dispatch_semaphore_signal; //发送一个信号

dispatch_semaphore_wait; //等待信号 

 

你可能感兴趣的:(Dispatch)