gpt4 book ai didi

ios - dispatch_semaphore_wait 不等待信号量

转载 作者:可可西里 更新时间:2023-11-01 06:19:10 47 4
gpt4 key购买 nike

我开发了以下方法,用于检查应用程序与服务器通信的能力。该方法执行一个简单的查询,并且知道如果得到结果,应用程序应该已连接(基本的 ping 机制)。

- (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 documentation 中建议的“dispatch_semaphore_wait”

我的目标是等待响应或短暂的超时以确定我们是否真的有有效连接。

对于上面的代码,“dispatch_semaphore_wait”实际上从未等待,即执行不会在该行停止,而是立即继续(总是返回 49 作为 dispatch_semaphore_wait 调用的结果)。那是除非我使用 DISPATCH_TIME_FOREVER 在这种情况下应用程序永远挂起......

目前我从主线程调用这个方法。我知道这是一个坏主意,但我希望在重构之前看到它按预期工作。

是什么导致了这种行为?谢谢。

最佳答案

dispatch_semaphore_wait的参数不是延时,而是信号量应该唤醒的时间。您将在 1 月 1 日午夜后 30 秒醒来。 1970 年(或 2001 年,不确定)。使用 dispatch_time 函数。

关于ios - dispatch_semaphore_wait 不等待信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25528695/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com