作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个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/
我是一名优秀的程序员,十分优秀!