consider this code block
public void ManageInstalledComponentsUpdate() { IUpdateView view = new UpdaterForm(); BackgroundWorker worker = new BackgroundWorker(); Update update = new Update(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += new DoWorkEventHandler(update.DoUpdate); worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback); worker.RunWorkerAsync(); Application.Run(view as UpdaterForm); }
It all works great but I want to understand why the objects (worker,view and update) don’t get garbage collected
Threads count as root objects; I don’t know exactly how BackgroundWorker operates, but it seems likely that the primary thread method is going to access state on the worker instance; as such, the worker thread itself will keep the BackgroundWorker instance alive until (at least) the thread has exited.
Of course; collection also requires that all other (live) objects have de-referenced the worker object; note also that collection of stack variables can be different in debug/release, and with/without a debugger attached.
[edit] As has also been noted; the event handlers on the worker (in your code) will keep the ‘view’ and ‘update’ objects alive (via the delegate), but not the other way around. As long as the worker has a shorter life than the ‘view’ and ‘update’, you don’t need to get paranoid about unsubscribing the events. I’ve edited the code to include a ‘SomeTarget’ object that isonly referenced by the worker: you should see this effect (i.e. the target dies with the worker).
Re worker getting collected when the thread dies: here’s the proof; you should see ‘worker finalized’ after the worker reports exit: