Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose a dictionary in C# best practice

Tags:

c#

.net

dispose

I have a ConcurrentDictionary in my session class.
Key is an interface representing a manager class.
Value is a List of DataContracts classes that are used for that manager in this session.

When I dispose the session class, I wish to clear this dictionary. I need to clear all values and keys, but i cant dispose the keys - since they still exists after class dispose..

Is this enough ? - will this cause the GC to do the work ?

_myDictionary = null;

Or i need to iterate with a foreach on all keys and use the Remove to clear values.

like image 922
ilansch Avatar asked Jun 24 '13 08:06

ilansch


1 Answers

When I dispose the session class, I wish to clear this dictionary.

Why? If the session instance is going to become eligible for garbage collection, and the session is the only object which refers to the dictionary, the dictionary will become eligible for garbage collection.

Is this enough ? - will this cause the GC to do the work ?

It's almost certainly unnecessary. If anything else has a reference to the dictionary, then setting that variable to null will have no effect. If nothing else has a reference to the dictionary and the session is going to become eligible for garbage collection, then you don't need to do this at all.

The only time it's worth setting a variable to null for the sake of garbage collection is when that variable itself will live on (e.g. it's an instance variable in an object which is not going to be garbage collected, or it's a static variable).

Note that garbage collection is entirely separate to "disposing" of objects, by the way. Dispose and IDisposable are generally concerned with unmanaged resources, and there's no indication in your question that that concept is relevant here.

like image 149
Jon Skeet Avatar answered Oct 25 '22 09:10

Jon Skeet