Garbage Collection and local variables to whose events a control has subscribed
If a c# class declares a variable, say an ObservableCollection, and subsequently subscribes to an event on that variable, does that prevent the control from being garbage collected. In other words, in the following circumstance, is the class SomeClass available for garbage collection:
开发者_运维百科public class SomeClass
{
private ObservableCollection<string> _someCollection = new ObservableCollection<string>();
public SomeClass()
{
_someCollection.CollectionChanged += OnSomeCollectionCollectionChanged;
}
private void OnSomeCollectionCollectionChanged(object sender,NotifyCollectionChangedEventArgs e )
{
}
}
Assuming nothing else has a reference to the ObservableCollection
, both of them will be eligible for garbage collection.
However, if something else keeps the ObservableCollection
alive, the reference from the collection to the SomeClass
instance (via the event) will keep the SomeClass
object alive too.
EDIT: To clarify the comments... the GC is quite capable of collecting two object which refer to each other, so long as nothing else is referring to them. For example:
/---->----\
X ---->---- Y Z
(root) \----<----/
Here object "X" is acting as a root, i.e. it's something the garbage collector knows should be kept alive (e.g. it's referred to from a local variable in a stack from of thread, or it's referred to via a static variable).
Now imagine that the reference from X to Y is severed:
/---->----\
X Y Z
(root) \----<----/
Now X is still kept alive as a GC root, but there are no "live" objects which refer to either Y or Z, so they can both be garbage collected. The fact that they refer to each other is irrelevant.
When you execute O.E += Y
(where E
is an event), object O
will have a reference to Y
. That means Y
cannot be collected until it either unsubscribes or O
gets collected. There is nothing to stop O
from getting collected.
精彩评论