【发布时间】:2017-11-12 20:05:10
【问题描述】:
我正在调用一个外部异步函数,该函数应在完成后调用回调。
然而,由于该函数是外部的,我不控制它的实现,我想设置一个超时 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);
}
}
【问题讨论】:
标签: objective-c multithreading cocoa-touch asynchronous timeout