How to timeout a future computation after a timeLimit?

半世苍凉 提交于 2020-02-21 13:14:30

问题


When defining a Future as follows:

Future<HttpRequest> httpRequest =  HttpRequest.request(url,
      method: method, requestHeaders: requestHeaders);

I want to handle a timeout after 5 secondes. I'm writing my code like this :

httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout());

Where my timeout function is :

_onTimeout() => print("Time Out occurs");

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

TimeException after 5 seconds... (TimeoutException after 0:00:05.000000: Future not completed )

Am I missing something ?


回答1:


Change this line

httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout());

to

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);

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()



来源:https://stackoverflow.com/questions/33897140/how-to-timeout-a-future-computation-after-a-timelimit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!