简体   繁体   中英

dispatch_async timeout method call

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

    });
});

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   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM