问题
I have a long running task that I want to run asynchronously with a Future, but I also want it to timeout eventually. It seems to me that my timeout is never being called - but perhaps I am not using timeout correctly?
// do actual solution finding asychronously
Future populateFuture = new Future(() {
populateGrid(words, gridWidth, gridHeight);
});
populateFuture.timeout(const Duration(seconds: 3), onTimeout: () {
window.alert("Could not create a word search in a reasonable amount of time.");
});
// after being done, draw it if one was found
populateFuture.then((junk) {
wordSearchGrid.drawOnce();
});
This is under version 1.3.0-dev.4.1 Perhaps I am just misunderstanding how to use timeout
回答1:
Dart has a single thread of execution.
Once a Dart function starts executing, it continues executing until it exits. In other words, Dart functions can’t be interrupted by other Dart code.
If populateGrid
doesn't allow the event loop to switch to the timeout
part the timeout
checks will not be executed. That means you have to break the code of populateGrid
into several part by introducing Future
computations to allow regular checks by the timeout
function.
回答2:
An example:
import 'dart:async';
import 'dart:math';
void main(args) {
var f = new Future(()=>burnCpu());
f.timeout(const Duration(seconds: 3));
}
bool signal = false;
int i = 0;
var r = new Random();
Future burnCpu() {
if (i < 1000000) {
i++;
return new Future(() { // can only interrupt here
print(i);
for (int j = 0; j < 1000000; j++) {
var a = (j / r.nextDouble()).toString() + r.nextDouble().toString();
}
}).then((e) => burnCpu());
} else {
return new Future.value('end');
}
}
来源:https://stackoverflow.com/questions/22471725/is-futures-timeout-method-broken