这本质上就是我同步运行异步方法所做的事情:
这在调用一次时基本上有效,但是当调用多次时,它最终将停留在 while 循环内并且永远不会收到信号。关于如何设置计时器在一段时间后最终超时有什么想法吗?
__block SomeClass *result = nil;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0UL);
dispatch_async(queue, ^{
[[SomeManager sharedInstance] someMethodWithCallback:^(id responseObject, NSError *error) {
if (!error) {
result = (SomeClass *)ResponseObject;
}
dispatch_semaphore_signal(semaphore);
}];
});
// wait with a time limit
while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]];
}
dispatch_release(semaphore);
谢谢
最佳答案
在我看来,这有点像 GCD 滥用。 ;) 您是否正在运行运行循环,因为它是在主线程上执行的?为什么不直接使用完成处理程序中的dispatch_async() 来调用主线程上的处理程序?例如:
- (void)handleDataReady: (id) results error: (NSError *) error {
// update your app
}
- (void)performAsyncUpdate {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0UL);
dispatch_async(queue, ^{
[[SomeManager sharedInstance] someMethodWithCallback:^(id responseObject, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[self handleDataReady:responseObject error:error];
}];
});
}
关于ios - 如何在同步运行时使异步方法超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17751510/