dispatch_async超时方法调用 [英] dispatch_async timeout method call

查看:133
本文介绍了dispatch_async超时方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设定的时间限制后,是否有一种好的方法可以调用外部方法来完成下面概述的长过程?我希望漫长的过程在设定的时间间隔后停止尝试,并调用方法尝试其他操作并包装请求.

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

  });
});

这篇关于dispatch_async超时方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆