dispatch_async timeout method call

£可爱£侵袭症+ 提交于 2019-12-04 19:32:46

In order to "kill" the process that's running your block, you'll have to check a condition. This will allow you to do cleanup. Consider the following modifications:

dispatch_async(dispatch_get_global_queue(0, 0), ^{

  BOOL finished = NO;
  __block BOOL cancelled = NO;
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    if (!finished) {
      cancelled = YES;
    }
  });

  void (^cleanup)() = ^{
    // CLEANUP
  };

  //// LONG PROCESS PORTION #1
  if (cancelled) {
    cleanup();
    return;
  }

  //// LONG PROCESS PORTION #2
  if (cancelled) {
    cleanup();
    return;
  }

  // etc.

  finished = YES;

  dispatch_async(dispatch_get_main_queue(), ^{

    //// RESULTS PROCESS

  });
});

In the ////Long Process change a boolean value (like BOOL finished) to true when finished. After the call to dispatch_async(...) you typed here, add this:

int64_t delay = 20.0; // In seconds
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^(void){
    if (!finished) {
        //// Stop process and timeout
    }
});

In this way, after 20 seconds (or any time you want) you can check if the process is still loading and take some provisions.

I've used this method for Swift:

let delay = 0.33 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

dispatch_after(time, dispatch_get_main_queue()) {
     //// RESULTS PROCESS   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!