dispatch_semaphore_wait不等待信号量 [英] dispatch_semaphore_wait does not wait on semaphore
问题描述
我开发了以下方法,该方法检查应用程序与服务器通信的能力.该方法执行一个简单的查询,并且知道如果得到结果,则应连接该应用程序(基本ping机制).
I have developed the following method, which checks the app's ability to communicate with the server. The method performs a simple query and knows that if it gets a result, the app should be connected (basic ping mechanism).
- (BOOL)isAppConnected
{
__block BOOL isConnected = NO;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[[SFRestAPI sharedInstance] performSOQLQuery:@"SELECT id FROM Account LIMIT 1"
failBlock:^(NSError *e) {
isConnected = NO;
NSLog(@"NOT CONNECTED %@", e);
NSLog(@"fail block ON THE MAIN THREAD? %hhd", [NSThread isMainThread]);
dispatch_semaphore_signal(semaphore);
} completeBlock:^(NSDictionary *dict) {
isConnected = YES;
NSLog(@"%@", dict);
NSLog(@"complete block ON THE MAIN THREAD? %hhd", [NSThread isMainThread]);
dispatch_semaphore_signal(semaphore);
}];
// if the wait times-out we will receive a non-zero result and can assume no connection to SF
//When using: DISPATCH_TIME_FOREVER the app hangs forever!!
int waitResult = dispatch_semaphore_wait(semaphore, 30 * NSEC_PER_SEC);
NSLog(@"waitResult: %d", waitResult);
return isConnected;
}
我正在使用 Apple文档
我的目标是等待响应或短暂的超时,以弄清我们是否真的有有效的连接.
My goal is to wait on the response or a short timeout to figure out if we really have a valid connection.
使用上面的代码,"dispatch_semaphore_wait"实际上从不等待,即执行不会在该行停止,而是立即继续(总是将49作为结果返回给dispatch_semaphore_wait调用).除非我使用DISPATCH_TIME_FOREVER,否则在这种情况下应用程序将永远挂起...
With the code above, 'dispatch_semaphore_wait' never actually waits, i.e. execution does not stop at that line but it continues immediately (always returning 49 as the result to the dispatch_semaphore_wait call). That is unless I use DISPATCH_TIME_FOREVER in which case the app hangs forever...
此刻,我正在从主线程调用此方法.我知道这是个坏主意,但我想在重构之前按预期工作.
At the moment I am calling this method from the main thread. I am aware that this is a bad idea, but I wanted to see this working as expected before refactoring.
什么可能导致此行为?谢谢.
What could be causing this behaviour? Thanks.
推荐答案
dispatch_semaphore_wait的参数不是延迟,而是信号量应唤醒的时间.1月1日午夜30秒后,您的手机将醒来.1970年(或2001年,不确定).使用dispatch_time函数.
The parameter for dispatch_semaphore_wait is not a delay, but the time when the semaphore should wake up. Yours will wake up 30 seconds after Midnight, Jan 1st. 1970 (or 2001, not sure). Use the dispatch_time function.
这篇关于dispatch_semaphore_wait不等待信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!