繁体   English   中英

如何中止JavaFX中的任务?

[英]How to abort a Task in JavaFX?

是否可以中止JavaFX中的Task 我的Task可能会遇到要取消其中其余操作的情况。

我将需要以某种方式返回一个值,以便在JFX Application Thread中处理中止的原因。

我见过的大多数相关答案都涉及到处理已经取消的任务,但是现在如何从任务本身内部手动取消它。

cancel()方法似乎无效,因为同时显示以下两条消息:

public class LoadingTask<Void> extends Task {

    @Override
    protected Object call() throws Exception {

        Connection connection;

        // ** Connect to server ** //
        updateMessage("Contacting server ...");
        try {
            connection = DataFiles.getConnection();
        } catch (SQLException ex) {
            updateMessage("ERROR: " + ex.getMessage());
            ex.printStackTrace();
            cancel();
            return null;
        }

        // ** Check user access ** //
        updateMessage("Verifying user access ...");
        try {
            String username = System.getProperty("user.name");
            ResultSet resultSet = connection.createStatement().executeQuery(
                    SqlQueries.SELECT_USER.replace("%USERNAME%", username));

            // If user doesn't exist, block access
            if (!resultSet.next()) {

            }
        } catch (SQLException ex) {

        }
        return null;
    }
}

和示例将不胜感激。

如果失败,为什么不让任务进入FAILED状态呢? 您所需要的(我还纠正了任务类型和调用方法返回类型的错误)是

public class LoadingTask extends Task<Void> {

    @Override
    protected Void call() throws Exception {

        Connection connection;

        // ** Connect to server ** //
        updateMessage("Contacting server ...");
        connection = DataFiles.getConnection();

        // ** Check user access ** //
        updateMessage("Verifying user access ...");
        String username = System.getProperty("user.name");
        ResultSet resultSet = connection.createStatement().executeQuery(
                SqlQueries.SELECT_USER.replace("%USERNAME%", username));

        // I am not at all sure what this is supposed to do....
        // If user doesn't exist, block access
        if (!resultSet.next()) {

        }
        return null;
    }
}

现在,如果DataFiles.getConnection()引发了异常,则调用方法会立即终止并出现异常(剩余的未执行),并且任务进入FAILED状态。 如果在出现问题的情况下需要访问异常,则可以执行以下操作:

LoadingTask loadingTask = new LoadingTask();
loadingTask.setOnFailed(e -> {
    Throwable exc = loadingTask.getException();
    // do whatever you need with exc, e.g. log it, inform user, etc
});
loadingTask.setOnSucceeded(e -> {
    // whatever you need to do when the user logs in...
});
myExecutor.execute(loadingTask);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM