<p>What are all the possible ways in which we can get memory leaks in .NET?</p>

<p>I know of two:</p>

<ol>
<li>Not properly un-registering <a href="http://diditwith.net/PermaLink,guid,fcf59145-3973-468a-ae66-aaa8df9161c7.aspx" rel="nofollow noreferrer">Event Handlers/Delegates</a>.</li>
<li>Not disposing dynamic child controls in Windows Forms:</li>
</ol>

<p>Example:</p>

<pre><code>// Causes Leaks  
Label label = new Label();  
this.Controls.Add(label);  
this.Controls.Remove(label);  

// Correct Code  
Label label = new Label();  
this.Controls.Add(label);  
this.Controls.Remove(label);  
label.Dispose();
</code></pre>

<p><strong>Update</strong>: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++.</p>

<hr>

<p>Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks.</p>

<p>In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question).</p>

<p><strong>So, what are the various possible ways in which such a memory leak can happen?</strong></p>

[{'answer_id': 20393, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 4, 'selected': False, 'text': '<p>There\'s no way to provide a comprehensive list... this is very much like asking "How can you get wet?"</p>\n\n<p>That said, make sure you\'re calling Dispose() on everything that implements IDisposable, and make sure you implement IDisposable on any types that consume unmanaged resources of any kind.</p>\n\n<p>Every now and then, run something like FxCop on your codebase to help you enforce that rule - you\'d be surprised how deep some disposable objects get buried within an application framework.</p>\n'}, {'answer_id': 20416, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 2, 'selected': False, 'text': '<p>Are you talking about unexpected memory usage or actual leaks? The two cases you listed aren\'t exactly leaks; they are cases where objects stick around longer than intended.</p>\n\n<p>In other words, they are references the person who calls them memory leaks didn\'t know or forgot about.</p>\n\n<p>Edit: Or they are actual bugs in the garbage collector or non-managed code.</p>\n\n<p>Edit 2: Another way to think about this is to always make sure external references to your objects get released appropriately. External means code outside of your control. Any case where that happens is a case where you can "leak" memory.</p>\n'}, {'answer_id': 20419, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 0, 'selected': False, 'text': '<p>A lot of the things that can cause memory leaks in unmanaged languages can still cause memory leaks in managed languages.  For example, <a href="http://blogs.msdn.com/oldnewthing/archive/2006/05/02/588350.aspx" rel="nofollow noreferrer">bad caching policies</a> can result in memory leaks.</p>\n\n<p>But as Greg and Danny have said, there is no comprehensive list.  Anything that can result in holding memory after its useful lifetime can cause a leak.</p>\n'}, {'answer_id': 20423, 'author': 'Rex M', 'author_id': 67, 'author_profile': 'https://Stackoverflow.com/users/67', 'pm_score': 2, 'selected': False, 'text': "<p>Calling IDisposable every time is the easiest place to start, and definitely an effective way to grab all the low-hanging memory leak fruit in the codebase. However, it is not always enough. For example, it's also important to understand how and when managed code is generated at runtime, and that once assemblies are loaded into the application domain, they are never unloaded, which can increase the application footprint.</p>\n"}, {'answer_id': 20431, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 4, 'selected': False, 'text': "<p>That doesn't really cause leaks, it just makes more work for the GC:</p>\n\n<pre><code>// slows GC\nLabel label = new Label();  \nthis.Controls.Add(label);  \nthis.Controls.Remove(label);  \n\n// better  \nLabel label = new Label();  \nthis.Controls.Add(label);  \nthis.Controls.Remove(label);  \nlabel.Dispose();\n\n// best\nusing( Label label = new Label() )\n{ \n    this.Controls.Add(label);  \n    this.Controls.Remove(label);  \n}\n</code></pre>\n\n<p>Leaving disposable components lying around like this is never much of a problem in a managed environment like .Net - that's a big part of what managed means.</p>\n\n<p>You'll slow you app down, certainly.  But you won't leave a mess for anything else.</p>\n"}, {'answer_id': 20469, 'author': 'Quibblesome', 'author_id': 1143, 'author_profile': 'https://Stackoverflow.com/users/1143', 'pm_score': 2, 'selected': False, 'text': '<p>Exceptions in Finalise (or Dispose calls from a Finaliser) methods that prevent unmanaged resources from being correctly disposed.\nA common one is due to the programmer <em>assuming</em> what order objects will be disposed and trying to release peer objects that have already been disposed resulting in an exception and the rest of the Finalise/Dispose from Finalise method not being called.</p>\n'}, {'answer_id': 24079, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 4, 'selected': True, 'text': '<p>Block the finalizer thread. No other objects will be garbage collected until the finalizer thread is unblocked. Thus the amount of memory used will grow and grow.</p>\n\n<p>Further reading: <a href="http://dotnetdebug.net/2005/06/22/blocked-finalizer-thread/" rel="nofollow noreferrer">http://dotnetdebug.net/2005/06/22/blocked-finalizer-thread/</a></p>\n'}, {'answer_id': 318679, 'author': 'Brian Rasmussen', 'author_id': 38206, 'author_profile': 'https://Stackoverflow.com/users/38206', 'pm_score': 0, 'selected': False, 'text': '<p>Deadlocked threads will never release roots. Obviously you could argue that the deadlock presents a bigger problem. </p>\n\n<p>A deadlocked finalizer thread will prevent all remaining finalizers to run and thus prevent all finalizable objects from being reclaimed (as they are still being rooted by the freachable list).</p>\n\n<p>On a multi CPU machine you could create finalizable objects faster than the finalizer thread could run finalizers. As long as that is sustained you will "leak" memory. It is probably not very likely that this will happen in the wild, but it is easy to reproduce. </p>\n\n<p>The large object heap is not compacted, so you could leak memory through fragmentation.</p>\n\n<p>There are a number of objects which must be freed manually. E.g. remoting objects with no lease and assemblies (must unload AppDomain).</p>\n'}, {'answer_id': 318744, 'author': 'Scott Langham', 'author_id': 11898, 'author_profile': 'https://Stackoverflow.com/users/11898', 'pm_score': 4, 'selected': False, 'text': '<p>Setting the <strong>GridControl.DataSource</strong> property directly without using an instance of the BindingSource class (<a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx</a>).</p>\n\n<p>This caused leaks in my application that took me quite a while to track down with a profiler, eventually I found this bug report that Microsoft responded to: <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=92260" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=92260</a></p>\n\n<p>It\'s funny that in the documentation for the BindingSource class Microsoft try to pass it off as a legitmate well thought out class, but I think they just created it to solve a fundamental leak regarding currency managers and binding data to grid controls.</p>\n\n<p>Watch out for this one, I bet there are absolutely loads of leaky applications out there because of this!</p>\n'}, {'answer_id': 1726553, 'author': 'Steve Townsend', 'author_id': 210102, 'author_profile': 'https://Stackoverflow.com/users/210102', 'pm_score': 1, 'selected': False, 'text': '<ol start="3">\n<li>Keeping around references to objects that you no longer need.</li>\n</ol>\n\n<p>Re other comments - one way to ensure Dispose gets called is to use using... when code structure allows it.</p>\n'}, {'answer_id': 3121169, 'author': 'John Hansen', 'author_id': 368423, 'author_profile': 'https://Stackoverflow.com/users/368423', 'pm_score': 2, 'selected': False, 'text': '<p>To prevent .NET memory leaks:</p>\n\n<p>1) Employ the \'using\' construct (or \'try-finally construct) whenever an object with \'IDisposable\' interface is created.</p>\n\n<p>2) Make classes \'IDisposable\' if they create a thread or they add an object to a static or long lived collection.  Remember a C# \'event\' is a collection.</p>\n\n<p>Here is a short article on <a href="http://yourdotnetdesignteam.blogspot.com/2010/06/tips-to-prevent-net-memory-leaks.html" rel="nofollow noreferrer">Tips to Prevent Memory Leaks</a>.</p>\n'}, {'answer_id': 3121231, 'author': 'Niki', 'author_id': 70915, 'author_profile': 'https://Stackoverflow.com/users/70915', 'pm_score': 1, 'selected': False, 'text': "<p>One thing that was really unexpected for me is this:</p>\n\n<pre><code>Region oldClip = graphics.Clip;\nusing (Region newClip = new Region(...))\n{\n    graphics.Clip = newClip;\n    // draw something\n    graphics.Clip = oldClip;\n}\n</code></pre>\n\n<p>Where's the memory leak? Right, you should have disposed <code>oldClip</code>, too! Because <code>Graphics.Clip</code> is one of the rare properties that returns a new disposable object every time the getter is invoked.</p>\n"}, {'answer_id': 3346674, 'author': 'user207331', 'author_id': 207331, 'author_profile': 'https://Stackoverflow.com/users/207331', 'pm_score': 2, 'selected': False, 'text': "<p>I have 4 additional items to add to this discussion:</p>\n\n<ol>\n<li><p>Terminating threads (Thread.Abort()) that have created UI Controls without properly preparing for such an event may lead to memory being used expectantly. </p></li>\n<li><p>Accessing unmanaged resources through Pinvoke and not cleaning them up may lead to memory leaks.</p></li>\n<li><p>Modifying large string objects. Not necessarily a memory leak, once out of scope, GC will take care of it, however, performance wise, your system may take a hit if large strings are modified often because you can not really depend on GC to ensure your program's foot print is minimal.</p></li>\n<li><p>Creating GDI objects often to perform custom drawing. If performing GDI work often, reuse a single gdi object.</p></li>\n</ol>\n"}, {'answer_id': 3353461, 'author': 'Valera Kolupaev', 'author_id': 29300, 'author_profile': 'https://Stackoverflow.com/users/29300', 'pm_score': 1, 'selected': False, 'text': '<p>Tess Fernandez Has great blog posts about finding and debugging memory leaks.\n<a href="http://blogs.msdn.com/b/tess/archive/2008/03/17/net-debugging-demos-lab-6-memory-leak-review.aspx" rel="nofollow noreferrer">Lab 6</a>  <a href="http://blogs.msdn.com/b/tess/archive/2008/04/03/net-debugging-demos-lab-7-memory-leak-review.aspx" rel="nofollow noreferrer">Lab 7</a></p>\n'}]
['https://Stackoverflow.com/questions/20386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380/']