【问题标题】:Objective-C Implement a timeout in non-blocking wayObjective-C 以非阻塞方式实现超时
【发布时间】: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


    【解决方案1】:

    您可以使用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);
        } 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多