对于异步循环,然后等待它完成(的OBJ-C)
问题描述:
因此,让我们假设我有以下代码对于异步循环,然后等待它完成(的OBJ-C)
-(void)doSomething{
[self expensiveMethod];
[self otherMethod]; //Depends on above method to have finished
}
-(void)expensiveMethod{
for(int i = 0; i<[someArray count]; i++{
[self costlyOperation:someArray[i]];
}
}
理想我想[self costlyOperation]
分拆其他线程使每一个为已完成接近并行(当然,我意识到这不是完全可能的)。一旦对每个数组对象完成了[self costlyOperation]
,我希望它返回,以便[self otherMethod
可以利用处理。
答
您可以使用默认队列在后台使用调度异步运行任务。
编辑
您可以并行执行ASYC组异步任务。您可能需要按照您的要求稍微调整一下。
-(void)doSomething{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
[self expensiveMethod:^{
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self otherMethod]; //Depends on above method to have finished
});
}];
});
}
-(void)expensiveMethod:(void (^)(void))callbackBlock {
dispatch_group_t group = dispatch_group_create();
for(int i = 0; i<[someArray count]; i++) {
__block int index = i;
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^{
[self costlyOperation:someArray[index]];
});
}
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^{
if (callbackBlock) {
callbackBlock();
}
});
}
那么这样的答案的一部分。另一部分在'expensiveMethod'里面,我想要并行运行for循环处理。 – user1416564
我编辑了答案。 – Bilal
谢谢!问题:我可以拥有的线程数是否有限制? – user1416564