1

I have a cache consisting of elements each of which contains two concurrent dictionary and I think they may be responsible for memory leak in my application. I'm frequently adding and removing stuff from this dictionary. Can someone provide me description of how memory allocation works for concurrent dictionary and what the best practice would be in my case? Thanks in advance!

Leonid Vasilev
  • 11,910
  • 4
  • 36
  • 50
  • 1
    None of the classes in .NET explicitly release allocated memory unless they are some specialty class designed to do just that. It will release the references, but it is up to to the garbage collector to de-allocate the memory for the object. I would recommend running a profiler on your program that can track object lifetimes and memory consumption and find out where your leek really is instead of guessing where it is. – Scott Chamberlain Dec 11 '13 at 07:56
  • Also if you are using 4.5.1 [there are some nice new classes to 4.0](http://msdn.microsoft.com/en-us/library/system.runtime.caching%28v=vs.110%29.aspx) for building caches of objects. – Scott Chamberlain Dec 11 '13 at 07:59
  • Thanks, that's what I really meant "will GC release memory which was used by removed element". So If I have a concurrent dictionary with some amount of elements, then I remove element from it and then after some time pass total amount of memory used by appication will decreased? Application use about 45GB of memory so it's kind of hard to use even WinDbg in this case. Other profiles stops working after application starts to use ~4GB. – Leonid Vasilev Dec 11 '13 at 08:08
  • You need to tell more about the "elements" and what you're doing with them. Maybe there are some remaining references? – JeffRSon Dec 11 '13 at 08:11

2 Answers2

4

Any .NET collection's remove method will not free the memory, it will simply remove the reference from the collection. If nothing else references those objects, the garbage collector will eventually clean them up.

A common cause of references being held are forgetting to unwire event handlers.

Several .NET Memory profilers such as MemProfiler, dotTrace and ANTS memory profiler have trial versions.

As @Scott Chamberlain points out, the System.Runtime.Caching Namespace contains types that let you implement caching in NET Framework applications.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • The `ConcurrentBag` implementation actually didn't always remove references immediately upon consuming them: http://stackoverflow.com/questions/5353164/possible-memoryleak-in-concurrentbag – Gabe Dec 11 '13 at 08:10
3

If the elements you are removing make use of unmanaged memory (bitmaps etc come to mind) these elements should implement IDisposable and you should call .Dispose before the last reference goes out of scope.

JeffRSon
  • 10,404
  • 4
  • 26
  • 51