iOS GCD(4)
[cpp]
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(@"waited at least 2.0 seconds.");
});
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(@"waited at least 2.0 seconds.");
});
值得注意的是,dispatch_after方法并不是在指定时间后执行处理任务,而是在指定时间后追加处理到dispatch queue中,上面的代码在2秒后用dispatch_after方法追加
block到Main Dispatch Queue中,因为Main Dispatch Queue在主线程的RunLoop中执行,所以比如每个1/60秒执行的RunLoop中,Block最快在2秒后执行,最慢在2秒+1/60
秒后执行,而且在Main Dispatch Queue中又大量处理追加或者主线程的处理本身有延时时,这个时间会更长。
dispatch_after这个方法的第二个参数指定要追加的dispatch queue,第三个参数指定要执行处理的Block,第一个参数是指定时间用的dispatch_time_t类型的值,在使用
dispatch_after的时候,编译器会自动帮你生成这些代码,只需修改delayInSeconds就可以了。
5、Dispatch Group
在追加到dispatch queue中的多个处理全部结束后想执行结束处理任务,这种情况会经常出现。只使用一个Serial Dispatch Queue时,只要将想执行的全部处理都追加到该
Serial Dispatch Queue种并在最后追加结束处理就可以实现。但是在使用Concurrent Dispatch Queue时或者同时使用多个dispatch queue时,就会有些复杂了,在这种情况下
就应该使用Dispatch Group
[cpp]
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{NSLog(@"blk1");});
dispatch_group_async(group, queue, ^{NSLog(@"blk2");});
dispatch_group_async(group, queue, ^{NSLog(@"blk3");});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"done");
});
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{NSLog(@"blk1");});
dispatch_group_async(group, queue, ^{NSLog(@"blk2");});
dispatch_group_async(group, queue, ^{NSLog(@"blk3");});
相关新闻>>
- 发表评论
-
- 最新评论 更多>>