R – the accepted pattern of killing background tasks in a WinForms app

backgroundworkerdisposenetwinforms

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?

Best Answer

You may want to hook into the Progress Changed Event. Have your worker invoke this event whenever it can safely be stopped without losing work. Now with this you can store the current state of the task by setting the value in ProgressChangedEventArgs and then you can restart where you left off without losing work.