I have a Hash table that takes strings. What is the best way to dispose them ? After using the hash table, should I call clear and then set the object to null ? Or would just setting the hash table object to null suffice ?
-
3you just do nothing, Garbage Collector will do it for youcuongle– cuongle2013-02-20 05:05:45 +00:00Commented Feb 20, 2013 at 5:05
-
GC can take hours to run. If you have an especially large dictionary, is it worthwhile to call the Clear() method in the Dispose() function? That's what I've always done.Brain2000– Brain20002015-07-15 18:33:24 +00:00Commented Jul 15, 2015 at 18:33
3 Answers
Others suggest not doing anything, and that is mostly true. You cannot dispose of it, in the classic C# sense of the term, and setting it to null should also prove unnecessary. The Garbage Collector will do its job if you let it.
So let it.
The piece of advice I have to offer that will help you let the garbage collector do its job is to limit the lifetime of the object to no longer than you need it. If the object only needs to live for a method invocation, then limit the scope of the variable and lifetime of the underlying object to that method, do not hoist it to a class member that might live longer. If the class sticks around an arbitrarily long time, that member state lives right along with it.
Declare the variable and instantiate the object where you need it, and only where you need it, and trust that the garbage collector will reclaim that memory at some point after you are through.
Comments
Setting a variable to null will not guarantee that it will be garbage collected. If other variables reference the same object the object in question will not be collected until the reference count goes to zero.
Limiting the scope of an object can help as the object is more likely to be collected after the object goes out of scope. Implementing idisposable really makes more sense for items that are not handed by garbage collection like file handles.
Comments
HashTable doesn't implement IDisposable so you can't call Dispose on it, you can assign the object null and let the garbage collector take care of it. You can't predict when it will be collected by the garbage collector, although you can force garbage collector with GC.Collect but its not recommended.
You may see: Fundamentals of Garbage Collection
Apart from this you may look into Dictionary<TKey, TValue> Class which is generic implementation of the HashTable.