title: Deallocate memory from C# dictionary contained in a static object
body: <p>I had some problems with a WCF web service (some dumps, memory leaks, etc.) and I run a profillng tool (ANTS Memory Profiles).</p>
  
  <p>Just to find out that even with the processing over (I run a specific test and then stopped), Generation 2 is 25% of the memory for the web service. I tracked down this memory to find that I had a dictionary object full of (null, null) items, with -1 hash code.</p>
  
  <p>The workflow of the web service implies that during specific processing items are added and then removed from the dictionary (just simple <code>Add</code> and <code>Remove</code>). Not a big deal. But it seems that after all items are removed, the dictionary is full of (null, null) <code>KeyValuePair</code>s. Thousands of them in fact, such that they occupy a big part of memory and eventually an overflow occurs, with the corresponding forced application pool recycle and DW20.exe getting all the CPU cycles it can get.</p>
  
  <p>The dictionary is in fact <code>Dictionary&lt;SomeKeyType, IEnumerable&lt;KeyValuePair&lt;SomeOtherKeyType, SomeCustomType&gt;&gt;&gt;</code> (<a href="https://stackoverflow.com/questions/5336011/system-outofmemoryexception-because-of-large-dictionary">System.OutOfMemoryException because of Large Dictionary</a>) so I already checked if there is some kind of reference holding things.</p>
  
  <p>The dictionary is contained in a static object (to make it accesible to different processing threads through processing) so from this question and many more (<a href="https://stackoverflow.com/questions/6600093/do-static-members-ever-get-garbage-collected">Do static members ever get garbage collected?</a>) I understand why that dictionary is in Generation 2. But this is also the cause of those (null, null)? Even if I remove items from dictionary something will be always occupied in the memory?</p>
  
  <p>It's not a speed issue like in this question <a href="https://stackoverflow.com/questions/3751871/deallocate-memory-from-large-data-structures-in-c-sharp">Deallocate memory from large data structures in C#</a> . It seems that memory is never reclaimed. </p>
  
  <p>Is there something I can do to actually remove items from dictionary, not just keep filling it with (null, null) pairs?
  Is there anything else I need to check out?</p>