取消任务不起作用

取消任务不起作用

本文介绍了JavaFX - 取消任务不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a JavaFX application, I have a method which takes a long time on large input. I'm opening a dialog when it is loading and I'd like the user to be able to cancel/close out the dialog and the task will quit. I created a task and added its cancellation in the cancel button handling. But the cancellation doesn't happen, the task doesn't stop executing.

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

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

Why isn't the task getting canceled when the button clicked?

推荐答案

您必须检查取消状态(参见)。看看这个:

You have to check on the cancel state (see 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...");
                }
            }
        }

    }

}

请注意......


  • 您应该使用而不是打印到 System.out ,这里仅用于演示。

  • 直接注入任务对象创建循环依赖项。但是,您可以使用代理或其他适合您情况的内容。

  • You should use Task#updateMessage(String) rather than printing to System.out, here it's just for demonstration.
  • Directly injecting the Task object creates a cyclic dependency. However, you can use a proxy or something else that fits your situation.

这篇关于JavaFX - 取消任务不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 18:25