JavaFX - 取消任务不起作用

JavaFX - Cancel Task doesn't work

在 JavaFX 应用程序中,我有一个方法在大量输入时需要很长时间。我在加载时打开一个对话框,我希望用户能够 cancel/close 退出对话框,任务将退出。我创建了一个任务并在取消按钮处理中添加了它的取消。但是取消并没有发生,任务没有停止执行。

Task<Void> task = new Task<Void>() {
    @Override
    public Void call() throws Exception {
        // calling a function that does heavy calculations in another class
    };
    task.setOnSucceeded(e -> {
        startButton.setDisable(false);
    });
}
new Thread(task).start();

cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
    System.out.println("Button handled");
    task.cancel();
}
);

为什么单击按钮后任务没有被取消?

您必须检查取消状态(参见 Task's Javadoc). Have a look at this MCVE:

public class Example extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                new AnotherClass().doHeavyCalculations(this);
                return null;
            }
        };

        Button start = new Button("Start");
        start.setOnMouseClicked(event -> new Thread(task).start());

        Button cancel = new Button("Cancel");
        cancel.setOnMouseClicked(event -> task.cancel());

        primaryStage.setScene(new Scene(new HBox(start, cancel)));
        primaryStage.show();
    }

    private class AnotherClass {

        public void doHeavyCalculations(Task<Void> task) {
            while (true) {
                if (task.isCancelled()) {
                    System.out.println("Canceling...");
                    break;
                } else {
                    System.out.println("Working...");
                }
            }
        }

    }

}

注意……

  • 你应该使用Task#updateMessage(String)而不是打印到System.out,这里只是为了演示。
  • 直接注入 Task 对象会产生循环依赖。但是,您可以使用代理或其他适合您情况的东西。