Recycle dictionary in C # best practice

I have a ConcurrentDictionary in my session class.
A key is an interface that represents a manager class.
The value is a list of the DataContracts classes that are used for this manager in this session.

When I delete a session class, I want to clear this dictionary. I need to clear all the values ​​and keys, but I cannot dispose of the keys - since they still exist after the dispose class ..

is that enough? - will it make the GC do the work?

_myDictionary = null; 

Or I need to iterate using foreach on all keys and use Remove to clear the values.

+8
c # dispose
source share
2 answers

When I delete a session class, I want to delete this dictionary.

Why? If the instance of the session has the right to garbage collection, and the session is the only object that refers to the dictionary, the dictionary will be suitable for garbage collection.

is that enough? - will it make the GC do the work?

It is almost certainly not necessary. If anything else has a dictionary reference, setting this variable to null will have no effect. If nothing else refers to the dictionary, and the session becomes suitable for garbage collection, you do not need to do this at all.

The only time it is worth setting a variable to null for garbage collection, the variable itself will exist (for example, it is an instance variable in an object that is not going to collect garbage, or a static variable).

Note that garbage collection is completely divided into "deletion" of objects, by the way. Dispose and IDisposable are usually associated with unmanaged resources, and there is no indication in your question that this concept matters here.

+16
source share

You can call GC.Collect(); immediately afterwards to make sure your GC is activated.

-one
source share

All Articles