dispatch_async timeout method call

雨燕双飞 提交于 2019-12-09 23:41:29

问题


Is there a good way to call an external method after a set time limit for completing the long process outlined below? I would like the long process to stop trying after a set interval and call a method to try something else and wrap up the request.

dispatch_async(dispatch_get_global_queue(0, 0), ^{

    //// LONG PROCESS

    dispatch_async(dispatch_get_main_queue(), ^{

        //// RESULTS PROCESS

    });
});

回答1:


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

  });
});



回答2:


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.




回答3:


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   
}


来源:https://stackoverflow.com/questions/26873239/dispatch-async-timeout-method-call

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