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

Mak*_*nko 1 multithreading cocoa-touch asynchronous timeout 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); } }

Ari*_*ris 7

您可以使用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);
    } 
});
Run Code Online (Sandbox Code Playgroud)