C# Garbage Collector question
I have a library which returns a hierarchical list composed of IDictionary, IList and primitive types (string, and ints). At present I cannot change how this data is returned.
I have another strongly typed class which is consuming this data and converting it into business objects. There is a list of "properties" in the data returned, which I want to import into my strongly typed class. I then can dispose of the hierarchy.
My question is this: If I do this:
MyCustomClass.Properties = HierarchicalData["some_name"]
Where MyCustomClass is my strongly typed class, and HierarchicalData is the IDictionary data what happens when I later call:
HierarchicalData = null
Can Hierarchical data be disposed and released? "some_data" in this case is another Dictionary and so technically that is all that needs to be kept. Do I need to do a explicit copy instead of importing, such as:
MyCustomClass.Properties = HierarchicalData["some_name"].ToDictionary<string, string>( /* selector */)
Clarification: I am not worried about the dictionary containing the properties being开发者_高级运维 garbage collected. I want to make sure that HierarchicalData __can__ be deleted as it is quite large and I need to work with several of them.
Yes. Once there are no references to HierarchicalData
, it will be a candidate for collection.
Since you have a reference to the data stored for the "some_name" key, that specific element (the other dictionary) will not be collected. However, the other, unreferenced, portions will become unrooted as far as the GC is concerned, and get finalized at some point.
This will work as you expect. Because you will have created a reference to the dictionary referenced by HierarchicalData["some_name"]
in another place, the garbage collector will keep it around for you.
You definitely do not need to copy the dictionary.
Assuming that the class returns a standard Dictionary<TKey, TValue>
, you probably don't need to do anything else.
The objects probably don't hold references to the dictionary that contains them, so they probably won't prevent the dictionary from being collected.
However, there's no way to be sure without checking; you should inspect the objects in the Visual Studio debugger's Watch window (or look at the source) and see whether they reference the dictionary.
You do not need to perform a copy.
The line:
MyCustomClass.Properties = HierarchicalData["some_name"]
assigns a reference, and while a reference to the object is alive, it will not be garbage collected.
Can Hierarchical data be disposed and released?
You mean by the GC? Not in this case, as it's referenced by your object(s). GC is not going to mess it up.
精彩评论