Explicitly freeing memory in c#

前端 未结 9 706
刺人心
刺人心 2020-12-01 01:12

I\'ve create a c# application which uses up 150mb of memory (private bytes), mainly due to a big dictionary:

Dictionary Txns = new Diction         


        
相关标签:
9条回答
  • 2020-12-01 02:05

    Do you need the memory back? The memory is available, it's just not being reclaimed. You should not clear the dictionary, hold a weak reference to it and let the runtime do its job.

    If you want to see really deep into what's going on, check out the .NET Memory Profiler. That will give you visibility into exactly what's happening with your object, what generation it is, what memory is being used by what and on and on. :)

    0 讨论(0)
  • 2020-12-01 02:07

    Most probably you have a hidden reference to the dictionary somewhere else. Thus the dictionary is not collected, but if you Clear() it, the contents get collected.

    As others have already noted, forcing the GC is not recommended. This might lead to memory being pushed into higher "generations" which are not often collected, thereby wasting more memory than gained in the long run.

    0 讨论(0)
  • 2020-12-01 02:15

    Ok, I have a theory here... Dictionary is a collection of KeyValuePair which is again a reference type.

    Your dictionary contains these keyValuePairs. When you say:

    Txns = null
    

    It frees the reference 'Txns' from those KeyValuePair collection. But still the actual memory of 150 Mb is being referenced by those KeyValuePair and they are in scope, thus not ready for garbage collection.

    But when you use the following:

    Txns.Clear();
    Txns = null;
    GC.Collect();
    

    Here, the clear method also frees the 150Mb of data from their respective KeyValuePair object references. Thus those objects were ready for garbage collection.

    Its just a wild guess I am making here. Comments are welcome :)

    0 讨论(0)
提交回复
热议问题