Swingworker Timeout

人盡茶涼 提交于 2019-12-20 01:35:08

问题


I am using a SwingWorker to read data over a TCP connection and display when it comes back.

new SwingWorker<EnvInfoProto, Void>() {
  @Override
  public EnvInfoProto doInBackground() {
    try {   
      xxx.writeTo(socket.getOutputStream());
      return ProtoMsg.parseFrom(socket.getInputStream());
    } catch(IOException ignore) { }
    return null;
  }

  @Override
  public void done() {
    try {
      UpdateGui(get());
    } catch (Exception ignore) {}
  }
}.execute();

The problem arises when the socket is dead, e.g. after writeTo it waits eternally for input on the socket. What is the easiest way to timeout after a while? Is this also the best solution in this case? Would I still use a swingworker in that solution?

Thanks


回答1:


Yes, the solution you linked to is a reasonable and easy solution ("best" is so subjective :) You could leverage SwingWorker#get, that is part of the Future interface:

SwingWorker<EnvInfoProto, Void> worker = new SwingWorker<EnvInfoProto, Void>() {
    ...
};
worker.execute();
worker.get(15, TimeUnit.SECONDS); 
//will block 15 seconds at most, then throw TimeoutException

Of course you could come up with different ways to reach your goal, but I'd bet there is more code involved than in this solution, so I'd give it a try.



来源:https://stackoverflow.com/questions/7042186/swingworker-timeout

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