I got a .net WinForms application. I have a UserControl which gets instantiated based on user action – upon instantiation, it performs some time-consuming tasks on a background thread (using BackgroundWorker), while displaying the ajaxy spinning animation. The user can click away at anytime, then click back onto the user control (which would start the background thread all over again).
When the user clicks away, I want to dispose of the UserControl and all the resources that it holds (including the background thread). What is the best way of doing this?
Call the CancelAsync method on the BackgroundWorker and wait for it to terminate. Construct your worker code so that it frequently checks for the cancel flag.
If there are no negative side effects if the thread continues to run for a while, and it will in no way reference the User Control or any resource held by it, you can dispose of the User Control after requesting the thread to terminate.
EDIT: Demo code