使用这样的调度组:
- (void)functionThatShouldBeSynchronous {
dispatch_group_t taskGroup = dispatch_group_create();
for (int i = 0; i < 10; i++) {
dispatch_group_enter(taskGroup);
[self doSomethingInBackground:^{
NSLog(@"completed!");
dispatch_group_leave(taskGroup);
}];
}
// Waiting for threads
dispatch_group_wait(taskGroup, DISPATCH_TIME_FOREVER);
dispatch_release(taskGroup);
// Background work complete
}
如果您希望等待线程超时,您可以将 dispatch_group_wait 行更改为此
// Waiting 10 seconds before giving up
if (dispatch_group_wait(taskGroup, dispatch_time(DISPATCH_TIME_NOW, 10000000000)) != 0) {
// Timeout
}
该参数以纳秒为单位。
正如 bbum 所说,你不应该阻塞主线程。在这种情况下,您可以这样做:
typedef void(^MyCompletionHandler)();
-(void)functionDoingBackgroundWorkWithCompletionHandler:(MyCompletionHandler)completionHandler {
dispatch_group_t taskGroup = dispatch_group_create();
for (int i = 0; i < 10; i++) {
dispatch_group_enter(taskGroup);
[self doSomethingInBackground:^{
NSLog(@"completed!");
dispatch_group_leave(taskGroup);
}];
}
dispatch_queue_t waitingQueue = dispatch_queue_create("com.mycompany.myapp.waitingQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(waitingQueue, ^{
// Waiting for threads
dispatch_group_wait(taskGroup, DISPATCH_TIME_FOREVER);
dispatch_release(taskGroup);
// Background work complete
dispatch_async(dispatch_get_main_queue(), ^{
// Calling the completion handler on the main thread (If you like)
completionHandler();
});
dispatch_release(waitingQueue);
});
}