如何在timeLimit之后使将来的计算超时? [英] How to timeout a future computation after a timeLimit?
问题描述
按以下方式定义Future时:
When defining a Future as follows:
Future<HttpRequest> httpRequest = HttpRequest.request(url,
method: method, requestHeaders: requestHeaders);
我想在5秒钟后处理超时。我正在这样写我的代码:
I want to handle a timeout after 5 secondes. I'm writing my code like this :
httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout());
我的超时功能是:
_onTimeout() => print("Time Out occurs");
根据将来的timeout()方法文档,如果省略了 onTimeout
,则超时将导致返回的Future完成与 TimeoutException
一起使用。但是用我的代码,我的方法 _onTimeout()
被正确调用了(但立即,不是在5秒后),并且我总是得到一个
According to the Future timeout() method documentation , If onTimeout
is omitted, a timeout will cause the returned future to complete with a TimeoutException
. But With my code , my method _onTimeout()
is properly called (but immediately, not after 5 seconds) and I always get a
5秒钟后出现TimeException ...(0:00:05.000000之后的TimeoutException:未来未完成)
TimeException after 5 seconds... (TimeoutException after 0:00:05.000000: Future not completed )
我失踪了什么?
推荐答案
更改此行
httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout());
到
httpRequest.timeout(const Duration (seconds:5),onTimeout : () => _onTimeout());
或仅传递对函数的引用(不带()
)
or just pass a reference to the function (without the ()
)
httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout);
这样,调用 _onTimeout()
将会传递给 timeout()
。
在以前的代码中, _onTimeout()
调用的结果将传递给 timeout()
This way the closure that calls _onTimeout()
will be passed to timeout()
.
In the former code the result of the _onTimeout()
call will be passed to timeout()
这篇关于如何在timeLimit之后使将来的计算超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!