gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:43:01 26 4
gpt4 key购买 nike

我有一个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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com