BackgroundWorker and resource managemnet in c#
Let suppose I create a background worker in a form as a component.And start it. Now if I close the form then BackgroundWorker will be sti开发者_StackOverflow中文版ll running. Will you explain that however form has been closed and all resources created within the form object have been closed but BackgroundWorker is still running. What is reason behind this?. Is this because of it is runnibg on a different thread. And when it resources will be regained by CLR.
The background worker isn't by default connected to the form or thread it's created in.
A background worker is an object like any other object. It will get collected when there are no more active references to it.
So it really depends on how and where the object was created, and mostly - who is still has references to it.
What people tend to forget is that the events are also references. So if there's another object somewhere that is listening to the worker's events, the worker will still be referenced and so it won't be collected.
Note:
Form.Close() removes the dialog from sight and calls the Closing() and Closed() methods. You can still access the form and bring it back later on.
Form.Dispose() destroys the dialog and frees its resources back to the operating system. It does not call the form’s Closing() and Closed() methods. Once disposed, you may not recall a form. The Dispose() will also call the Dispose() method of all the Form's components.
The background worker will be disposed with the form, unless you deliberately suppress dispose. If this is the case then it should be garbage collected at an indeterminate time. I say should because things could potentially hold reference to the background worker. As for the thread, I believe it will be cleaned in the dispose, which should be called from the form when it closes.
If the form is the main form, and on closing causes the main foreground thread to close, then all background threads will close / die also.
When you close your form and dispose it, BackgroundWorker will dispose too, but it does not stop the thread running. So it will be completely destroyed only after the DoWork finishes.
You can solve this by cancelling the closing of the Form and calling CancelAsync
on the background worker to signal that you want it to finish. Wait until it finishes and only after that you should actually close the form.
精彩评论