我有类似的代码:
timer = new Timer(new Duration(milliseconds: 1000), () => (throw new TimeoutException('Callback not invoked!')));
while (timer.isActive){
await new Future.delayed(const Duration(milliseconds: 1), () => "1");
}
print('this should not be reached if the exception is raised');
Run Code Online (Sandbox Code Playgroud)
在其他地方我有一个异步回调,它调用:
timer.cancel();
Run Code Online (Sandbox Code Playgroud)
在调用回调的情况下,它工作正常,因为回调取消了计时器。
但是,我不太确定TimeoutException在这种情况下如果没有取消,如何实际捕获它,因为似乎异常是在与我的主函数不同的范围内引发的。这意味着即使
有没有办法进行某种 try/catch 或以某种方式处理上述超时异常?或者有更好的方法来做我想做的事情?
使用 dart 1.19.1。
根据超时是否为500ms或 ,您会得到不同的行为1500ms:
final timer = new Future.delayed(const Duration(milliseconds: 1000),
() => (throw new Exception('Callback not invoked!')))
.timeout(const Duration(milliseconds: 500));
try {
await timer;
} on TimeoutException catch(e) {
print('this should not be reached if the exception is raised');
} on Exception catch(e) {
print('exception: $e');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6050 次 |
| 最近记录: |