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

马克西姆邦达连科

我正在调用一个外部异步函数,该函数在完成后应调用回调。
但是,由于该函数是外部函数,我不控制它的实现,我想设置一个 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);
    } 
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章