tags:

views:

42

answers:

1

If I have started a SwingWorker thread by invoking its execute(). Is there any way that I can interrupt it at its execution?

+4  A: 

If you control the code of the SwingWorker, you can poll isCancelled() at appropriate places in doInBackground(), and then stop doing work if it returns true. Then cancel the worker when you feel like it:

class YourWorker extends SwingWorker<Foo, Bar> {

    // ...

    protected Foo doInBackground() throws Exception {
        while (someCondition) {
            publish(doSomeIntermediateWork());
            if (isCancelled())
                return null; // we're cancelled, abort work
        }
        return calculateFinalResult();
    }

}

// To abort the task:
YourWorker worker = new YourWorker(args);
worker.execute();
doSomeOtherStuff();
if (weWantToCancel)
    worker.cancel(false); // or true, doesn't matter to us here

Now, as you noted, cancel(boolean) can fail, but why? The Javadocs inform us:

Returns:

false if the task could not be cancelled, typically because it has already completed normally; true otherwise.

gustafc
that is great! many thanks!
dolaameng