是否可以在JavaFX中中止Task
?我的Task
可能会遇到我想取消其中其余操作的情况。
我需要以某种方式返回一个值,以便我可以处理JFX应用程序线程中的中止原因。
我见过的大多数相关答案都是指处理已经取消的任务,但现在如何从任务本身手动取消它。
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;
}
}
非常感谢示例。
答案 0 :(得分:0)
如果失败,为什么不让任务进入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);