gpt4 book ai didi

objective-c - Objective-C以非阻塞方式实现超时

转载 作者:行者123 更新时间:2023-12-03 13:17:01 25 4
gpt4 key购买 nike

我正在调用一个外部异步函数,该函数应在完成后立即调用回调。
但是,由于该函数是外部函数,因此我不控制其实现,并且我想以5秒钟为例设置超时,并考虑如果在这5天内未传递给该外部异步函数的回调调用了超时的操作秒。

我目前发现的唯一方法是使当前线程进入休眠状态,从而实际上阻塞了该线程。
这是一个例子:
+(void)myFuncWithCompletion:(void (^ _Nonnull)(BOOL))completion{
BOOL timedOut = NO;
BOOL __block finishedAsyncCall = NO;
[someObj someAsyncMethod {
// completion callback
finishedAsyncCall = YES;
if (!timedOut) {
completion(YES);
}
}];
// This is the logic I want to fix. My goal is to make something similar but non-blocking.
long timeoutInSeconds = 5;
long startTime = [[NSDate date] timeIntervalSince1970];
long currTime = [[NSDate date] timeIntervalSince1970];
while (!finishedAsyncCall && startTime + timeoutInSeconds > currTime) {
[NSThread sleepForTimeInterval:0];
currTime = [[NSDate date] timeIntervalSince1970];
}
if (!finishedAsyncCall) {
timedOut = YES;
completion(NO);
}
}

最佳答案

您可以使用dispatch_after代替-[NSThread sleepForTimeInterval:]

double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); // 1
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // 2
if (!finishedAsyncCall ) {
timedOut = YES;
completion(NO);
}
});

关于objective-c - Objective-C以非阻塞方式实现超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44480922/

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