asynchronous - 如何在Dart中取消/中止区域?

标签 asynchronous dart future zone dart-shelf

我有一个http Web服务器,该服务器试图检测长时间运行的请求并中止它们。以下代码在超时后成功返回到客户端,但是异步区域仍然继续运行直至完成。 我实际上如何杀死请求处理程序?

var zone = runZoned(() {
  var timer = new Timer(new Duration(seconds: Config.longRequestTimeoutSeconds), () {
    if (!completer.isCompleted) { // -- not already completed
      log.severe('request timed out');
      // TODO: This successfully responds to the client early, but it does nothing to abort the zone/handler that is already running.
      //       Even though the client will never see the result (and won't have to wait for it), the zone/handler will continue to run to completion as normal.
      // TODO: Find a way to kill/abort/cancel the zone
      completer.complete(new shelf.Response(HttpStatus.SERVICE_UNAVAILABLE, body: 'The server timed out while processing the request'));
    }
  });

  return innerHandler(request) // -- handle request as normal (this may consist of several async futures within)
    .then((shelf.Response response) {
      timer.cancel(); // -- prevent the timeout intercept
      if (!completer.isCompleted) { // -- not already completed (not timed out)
        completer.complete(response);
      }
    })
    .catchError(completer.completeError);
});

最佳答案

除了本身,没有什么可以杀死正在运行的代码。如果您希望代码是可中断的,则需要某种方法来告知它,并且代码本身需要终止(可能会引发错误)。在这种情况下,innerHandler需要能够在被请求时自行中断。如果不是您的代码,那可能是不可能的。

您可以编写一个区域,以在设置标志时停止执行异步事件(通过修改Zone.run等),但是您必须非常小心-如果您开始扔掉它,它可能永远不会到达异步的finally块并释放资源。异步事件。因此,不建议将其作为一般解决方案,仅用于非常愿意进行手动资源管理的人员。

关于asynchronous - 如何在Dart中取消/中止区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529328/

相关文章:

c - 无需轮询的 Linux 同步

javascript - 在 Promise 返回函数中找到第一个成功

javascript - 了解 Dart 1.11 的新 appendHTML 清理

javascript - Fluture bimap 和 fold,有什么区别,我应该什么时候使用它们?

java - 在 Java 中将监听器变成 future

promise - Vert.x 3.8.1+ 中 CompositeFuture 的 Promise 等价物是什么?

c++ - 使用 WxWidgets 异步执行

c# - MongoDB .NET 驱动程序查找全部 : How to write it better?

dart - Dart :在命令行应用程序中移动光标

dart - 如何仅将填充应用于 Flutter 中 TextField 中的文本?