how can a file upload / download operation be cancelled without terminating the thread that performs this operation?

StackOverflow https://stackoverflow.com/questions/17615877

Question

My code calls an API method that downloads a file from the internet. Because the download can take a large amount of time, I would like to provide the user with the ability to cancel the download if they close the window that shows the progress bar while a background thread handles the file download.

I'm not sure I have any control over the code called by the API method, so I'm assuming that I don't have an option to signal this code that the download operation needs to be cancelled.

If this assumption is correct, how do I terminate the file download operation on user request without having to abort/interrupt or otherwise terminate the background thread that performs the actual file download?

Was it helpful?

Solution

I would expect a properly-designed file download method to be interruptible. So you need to interrupt the thread in which the download is being done, which should cancel the download (the method should throw an InterruptedException).

Once you have caught the exception from the downloading thread, you can then decide what to do, for example wait for a new file download to be submitted (i.e. not exit).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top