2

There is a lot of information about how to cancel/stop a SwingWorker. However I can not find a proper solution on how to stop a long lasting method started within the doInBackround() method when cancel is invoked from the EDT.

For instance, if a recursive file search is started within the doInBackround() method using org.apache.commons.io.FileUtils.listFiles(file, FileUtils.getFileFilter(), DirectoryFileFilter.DIRECTORY);, and cancel(true) is invoked from the EDT, how can the file search be interrupted?

Rico Leuthold
  • 1,975
  • 5
  • 34
  • 49

1 Answers1

2

You need collaboration from the background task to be able to stop it. It should regularly check if the task has been cancelled and return as soon as possible if cancelled.

So, either you reimplement the listFiles() method yourself and check at each iteration that the task hasbn't been cancelled, or you use a dirty trick, and throw some runtime exception from inside the file filter if the task has been cancelled (since the file filter will be invoked for every file the listFiles() method inspects.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Wow, looking at the commons IO source code that seems to be quite an effort to do it the proper way. I was afraid that something like this might be the answer :-) Thank you anyway! – Rico Leuthold Jun 21 '12 at 12:06
  • Just wanted to let you know that it works perfect with an adapted version of `listFiles()`. Thank you again. – Rico Leuthold Jun 22 '12 at 11:58