Is Future's timeout method broken?

爱⌒轻易说出口 提交于 2019-12-24 05:25:15

问题


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

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