<p>The .NET garbage collector will eventually free up memory, but what if you want that memory back immediately? What code do you need to use in a class <code>MyClass</code> to call</p>

<pre><code>MyClass.Dispose()
</code></pre>

<p>and free up all the used space by variables and objects in <code>MyClass</code>?</p>

[{'answer_id': 12376, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.codeguru.com/csharp/.net/net_general/tipstricks/article.php/c7047/" rel="nofollow noreferrer" title="Forcing Garbage Collection in .Net">This article</a> has a pretty straightforward walkthrough.  However, <em>having</em> to call the GC instead of letting it take its natural course is generally a sign of bad design/memory management, <strong>especially</strong> if no limited resources are being consumed (connections, handles, anything else that typically leads to implementing IDisposable).</p>\n\n<p>What\'s causing you to need to do this?</p>\n'}, {'answer_id': 12377, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public class MyClass : IDisposable\n{\n    public void Dispose()\n    {\n       // cleanup here\n    }\n}\n</code></pre>\n\n<p>then you can do something like this</p>\n\n<pre><code>MyClass todispose = new MyClass();\ntodispose.Dispose(); // instance is disposed right here\n</code></pre>\n\n<p>or</p>\n\n<pre><code>using (MyClass instance = new MyClass())\n{\n\n}\n// instance will be disposed right here as it goes out of scope\n</code></pre>\n'}, {'answer_id': 12380, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 0, 'selected': False, 'text': "<p>If MyClass implements IDisposable you can do just that.</p>\n\n<pre><code>MyClass.Dispose();\n</code></pre>\n\n<p>Best practice in C# is:</p>\n\n<pre><code>using( MyClass x = new MyClass() ) {\n    //do stuff\n}\n</code></pre>\n\n<p>As that wraps up the dispose in a try-finally and makes sure that it's never missed.</p>\n"}, {'answer_id': 12383, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 0, 'selected': False, 'text': "<p>If you don't want to (or can't) implement IDisposable on your class, you can force garbage collection like this (but it's slow) -</p>\n\n<pre><code>GC.Collect();\n</code></pre>\n"}, {'answer_id': 12394, 'author': 'Curt Hagenlocher', 'author_id': 533, 'author_profile': 'https://Stackoverflow.com/users/533', 'pm_score': 8, 'selected': True, 'text': '<p>IDisposable has nothing to do with freeing memory.  IDisposable is a pattern for freeing <em>unmanaged</em> resources -- and memory is quite definitely a managed resource.</p>\n\n<p>The links pointing to GC.Collect() are the correct answer, though use of this function is generally discouraged by the Microsoft .NET documentation.</p>\n\n<p><strong>Edit:</strong> Having earned a substantial amount of karma for this answer, I feel a certain responsibility to elaborate on it, lest a newcomer to .NET resource management get the wrong impression.</p>\n\n<p>Inside a .NET process, there are two kinds of resource -- managed and unmanaged.  "Managed" means that the runtime is in control of the resource, while "unmanaged" means that it\'s the programmer\'s responsibility.  And there really is only one kind of managed resource that we care about in .NET today -- memory.  The programmer tells the runtime to allocate memory and after that it\'s up to the runtime to figure out when the memory can freed.  The mechanism that .NET uses for this purpose is called <a href="http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)" rel="noreferrer">garbage collection</a> and you can find plenty of information about GC on the internet simply by using Google.</p>\n\n<p>For the other kinds of resources, .NET doesn\'t know anything about cleaning them up so it has to rely on the programmer to do the right thing.  To this end, the platform gives the programmer three tools:</p>\n\n<ol>\n<li>The IDisposable interface and the "using" statement in VB and C#</li>\n<li>Finalizers</li>\n<li>The IDisposable pattern as implemented by many BCL classes</li>\n</ol>\n\n<p>The first of these allows the programmer to efficiently acquire a resource, use it and then release it all within the same method.</p>\n\n<pre><code>using (DisposableObject tmp = DisposableObject.AcquireResource()) {\n    // Do something with tmp\n}\n// At this point, tmp.Dispose() will automatically have been called\n// BUT, tmp may still a perfectly valid object that still takes up memory\n</code></pre>\n\n<p>If "AcquireResource" is a factory method that (for instance) opens a file and "Dispose" automatically closes the file, then this code cannot leak a file resource.  But the memory for the "tmp" object itself may well still be allocated.  That\'s because the IDisposable interface has absolutely no connection to the garbage collector.  If you <em>did</em> want to ensure that the memory was freed, your only option would be to call <code>GC.Collect()</code> to force a garbage collection.</p>\n\n<p>However, it cannot be stressed enough that this is probably not a good idea.  It\'s generally much better to let the garbage collector do what it was designed to do, which is to manage memory.</p>\n\n<p>What happens if the resource is being used for a longer period of time, such that its lifespan crosses several methods?  Clearly, the "using" statement is no longer applicable, so the programmer would have to manually call "Dispose" when he or she is done with the resource.  And what happens if the programmer forgets?  If there\'s no fallback, then the process or computer may eventually run out of whichever resource isn\'t being properly freed.</p>\n\n<p>That\'s where finalizers come in.  A finalizer is a method on your class that has a special relationship with the garbage collector.  The GC promises that -- before freeing the memory for any object of that type -- it will first give the finalizer a chance to do some kind of cleanup.</p>\n\n<p>So in the case of a file, we theoretically don\'t need to close the file manually at all.  We can just wait until the garbage collector gets to it and then let the finalizer do the work.  Unfortunately, this doesn\'t work well in practice because the garbage collector runs non-deterministically.  The file may stay open considerably longer than the programmer expects.  And if enough files are kept open, the system may fail when trying to open an additional file.</p>\n\n<p>For most resources, we want both of these things.  We want a convention to be able to say "we\'re done with this resource now" and we want to make sure that there\'s at least some chance for the cleanup to happen automatically if we forget to do it manually.  That\'s where the "IDisposable" pattern comes into play.  This is a convention that allows IDispose and a finalizer to play nicely together.  You can see how the pattern works by looking at the <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="noreferrer">official documentation for IDisposable</a>.</p>\n\n<p><strong>Bottom line:</strong> If what you really want to do is to just make sure that memory is freed, then IDisposable and finalizers will not help you.  But the IDisposable interface is part of an extremely important pattern that all .NET programmers should understand.</p>\n'}, {'answer_id': 12396, 'author': 'Brian Lyttle', 'author_id': 636, 'author_profile': 'https://Stackoverflow.com/users/636', 'pm_score': 4, 'selected': False, 'text': "<p>Would it be appropriate to also mention that dispose doesn't always refer to memory? I dispose resources such a references to files more often than memory. GC.Collect() directly relates to the CLR garbage collector and may or may not free memory (in Task Manager). It will likely impact your application in negative ways (eg performance).</p>\n\n<p>At the end of the day why do you want the memory back immediately? If there is memory pressure from elsewhere the OS will get you memory in most cases.</p>\n"}, {'answer_id': 12398, 'author': 'Booji Boy', 'author_id': 1433, 'author_profile': 'https://Stackoverflow.com/users/1433', 'pm_score': 2, 'selected': False, 'text': "<p>You can't really force a GC to clean up an object when you want, although there are ways to force it to run, nothing says it's clean up the all the object you want/expect. It's best to call dispose in a try catch ex finally dispose end try (VB.NET rulz) way. But Dispose is for cleaning up system resources (memory, handles, db connections, etc. allocated by the object in deterministic way. Dispose doesn't (and can't) clean up the memory used by the object itself, only the the GC can do that.      </p>\n"}, {'answer_id': 12405, 'author': 'Patrik Svensson', 'author_id': 936, 'author_profile': 'https://Stackoverflow.com/users/936', 'pm_score': 5, 'selected': False, 'text': '<p>You can only dispose instances that implement the IDisposable interface.  </p>\n\n<p><strong>To force a garbage collect to free up the (unmanaged) memory immediately:</strong></p>\n\n<pre><code>GC.Collect();  \nGC.WaitForPendingFinalizers();\n</code></pre>\n\n<p>This is normally bad practice, but there is for example a bug in the x64-version of the .NET framework that makes the GC behave strange in some scenarios, and then you might want to do this. I don\'t know if the bug have been resolved yet. Does anyone know?</p>\n\n<p><strong>To dispose a class you do this:</strong></p>\n\n<pre><code>instance.Dispose();\n</code></pre>\n\n<p>or like this:</p>\n\n<pre><code>using(MyClass instance = new MyClass())\n{\n    // Your cool code.\n}\n</code></pre>\n\n<p>that will translate at compile-time to:</p>\n\n<pre><code>MyClass instance = null;    \n\ntry\n{\n    instance = new MyClass();        \n    // Your cool code.\n}\nfinally\n{\n    if(instance != null)\n        instance.Dispose();\n}\n</code></pre>\n\n<p><strong>You can implement the IDisposable interface like this:</strong></p>\n\n<pre><code>public class MyClass : IDisposable\n{\n    private bool disposed;\n\n    /// &lt;summary&gt;\n    /// Construction\n    /// &lt;/summary&gt;\n    public MyClass()\n    {\n    }\n\n    /// &lt;summary&gt;\n    /// Destructor\n    /// &lt;/summary&gt;\n    ~MyClass()\n    {\n        this.Dispose(false);\n    }\n\n    /// &lt;summary&gt;\n    /// The dispose method that implements IDisposable.\n    /// &lt;/summary&gt;\n    public void Dispose()\n    {\n        this.Dispose(true);\n        GC.SuppressFinalize(this);\n    }\n\n    /// &lt;summary&gt;\n    /// The virtual dispose method that allows\n    /// classes inherithed from this one to dispose their resources.\n    /// &lt;/summary&gt;\n    /// &lt;param name="disposing"&gt;&lt;/param&gt;\n    protected virtual void Dispose(bool disposing)\n    {\n        if (!disposed)\n        {\n            if (disposing)\n            {\n                // Dispose managed resources here.\n            }\n\n            // Dispose unmanaged resources here.\n        }\n\n        disposed = true;\n    }\n}\n</code></pre>\n'}, {'answer_id': 12470, 'author': 'Tundey', 'author_id': 1453, 'author_profile': 'https://Stackoverflow.com/users/1453', 'pm_score': 0, 'selected': False, 'text': "<p>IDisposable interface is really for classes that contain unmanaged resources. If your class doesn't contain unmanaged resources, why do you <strong>need</strong> to free up resources before the garbage collector does it? Otherwise, just ensure your object is instantiated as late as possible and goes out of scope as soon as possible.</p>\n"}, {'answer_id': 13649, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 3, 'selected': False, 'text': '<p>Take a look at this <a href="http://www.codeproject.com/KB/cs/idisposable.aspx" rel="nofollow noreferrer">article</a></p>\n\n<p>Implementing the Dispose pattern, IDisposable, and/or a finalizer has absolutely nothing to do with when memory gets reclaimed; instead, it has everything to do with telling the GC <strong><em>how</em></strong> to reclaim that memory. When you call Dispose() you are in no way interacting with the GC.</p>\n\n<p>The GC will only run when it determines the need to (called memory pressure) and then (and only then) will it deallocate memory for unused objects and compact the memory space.</p>\n\n<p>You <em>could</em> call GC.Collect() but you really shouldn\'t unless there is a <strong>very</strong> good reason to (which is almost always "Never"). When you force an out-of-band collection cycle like this you actually cause the GC to do more work and ultimately can end up hurting your applications performance. For the duration of the GC collection cycle your application is actually in a frozen state...the more GC cycles that run, the more time your application spends frozen.</p>\n\n<p>There are also some native Win32 API calls you can make to free your working set, but even those should be avoided unless there is a <strong>very</strong> good reason to do it.</p>\n\n<p>The whole premise behind a gargbage collected runtime is that you don\'t need to worry (as much) about when the runtime allocates/deallocates actual memory; you only need to worry about making sure the your object knows how to clean up after itself when asked.</p>\n'}, {'answer_id': 19463, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 0, 'selected': False, 'text': "<p>You can have deterministic object destruction in c++</p>\n\n<p>You never want to call GC.Collect, it messes with the self tuning of the garbage collector to detect memory pressure and in some cases do nothing other than increase the current generation of every object on the heap. </p>\n\n<p>For those posting IDisposable answers.  Calling a Dispose method doesn't destroy an object as the asker describes.</p>\n"}, {'answer_id': 26949, 'author': 'Shaun Austin', 'author_id': 1120, 'author_profile': 'https://Stackoverflow.com/users/1120', 'pm_score': 1, 'selected': False, 'text': "<p>Sorry but the selected answer here is incorrect. As a few people have stated subsequently Dispose and implementing IDisposable has nothing to do with freeing the memory associated with a .NET class. It is mainly and traditionally used to free unmanaged resources such as file handles etc.</p>\n\n<p>While your application can call GC.Collect() to try to force a collection by the garbage collector this will only really have an effect on those items that are at the correct generation level in the freachable queue. So it is possible that if you have cleared all references to the object it might still be a couple of calls to GC.Collect() before the actual memory is freed.</p>\n\n<p>You don't say in your question WHY you feel the need to free up memory immediately. I understand that sometimes there can be unusual circumstances but seriously, in managed code it is almost always best to let the runtime deal with memory management.</p>\n\n<p>Probably the best advice if you think your code is using up memory quicker than the GC is freeing it then you should review your code to ensure that no objects that are no longer needed are referenced in any data structures you have lying around in static members etc. Also try to avoid situations where you have circular object references as it is possible that these may not be freed either. </p>\n"}, {'answer_id': 27597, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 0, 'selected': False, 'text': '<p>@Curt Hagenlocher - that\'s back to front. I\'ve no idea why so many have voted it up when it\'s wrong.</p>\n\n<p><code>IDisposable</code> is for <em>managed</em> resources.</p>\n\n<p>Finalisers are for <em>unmanaged</em> resources.</p>\n\n<p>As long as you only use managed resources both @Jon Limjap and myself are entirely correct.</p>\n\n<p>For classes that use unmanaged resources (and bear in mind that the vast majority of .Net classes don\'t) Patrik\'s answer is comprehensive and best practice.</p>\n\n<p>Avoid using GC.Collect - it is a slow way to deal with managed resources, and doesn\'t do anything with unmanaged ones unless you have correctly built your ~Finalizers.</p>\n\n<hr>\n\n<p>I\'ve removed the moderator comment from the original question in line with <a href="https://stackoverflow.com/questions/14593/etiquette-for-modifying-posts">https://stackoverflow.com/questions/14593/etiquette-for-modifying-posts</a></p>\n'}, {'answer_id': 27608, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 0, 'selected': False, 'text': '<p>@Keith:</p>\n<blockquote>\n<p>IDisposable is for managed resources.</p>\n<p>Finalisers are for unmanaged resources.</p>\n</blockquote>\n<p>Sorry but that\'s just wrong. Normally, the finalizer does nothing at all. However, if the <a href="http://blogs.msdn.com/bclteam/archive/2007/10/30/dispose-pattern-and-object-lifetime-brian-grunkemeyer.aspx" rel="nofollow noreferrer">dispose pattern</a> has been correctly implemented, the finalizer tries to invoke <code>Dispose</code>.</p>\n<p><code>Dispose</code> has two jobs:</p>\n<ul>\n<li>Free unmanaged resources, and</li>\n<li>free nested managed resources.</li>\n</ul>\n<p>And here your statement comes into play because it\'s true that while finalizing, an object should never try to free nested managed resources as these may have already been freed. It must still free unmanaged resources though.</p>\n<p>Still, finalizers have no job other than to call <code>Dispose</code> and tell it not to touch managed objects. <code>Dispose</code>, when called manually (or via <code>Using</code>), shall free all unmanaged resources and pass the <code>Dispose</code> message on to nested objects (and base class methods) but this will <em>never</em> free any (managed) memory.</p>\n'}, {'answer_id': 27630, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 0, 'selected': False, 'text': '<p>Konrad Rudolph - yup, normally the finaliser does nothing at all. You shouldn\'t implement it unless you are dealing with unmanaged resources.</p>\n\n<p>Then, when you do implement it, you use <a href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx" rel="nofollow noreferrer">Microsoft\'s dispose pattern</a> (as already described)</p>\n\n<ul>\n<li><p><code>public Dispose()</code> calls <code>protected Dispose(true)</code> - deals with both managed and unmanaged resources. Calling <code>Dispose()</code> should suppress finalisation.</p></li>\n<li><p><code>~Finalize</code> calls <code>protected Dispose(false)</code> - deals with unmanaged resources only. This prevents unmanaged memory leaks if you fail to call the <code>public Dispose()</code></p></li>\n</ul>\n\n<p><code>~Finalize</code> is slow, and shouldn\'t be used unless you do have unmanaged resources to deal with.</p>\n\n<p>Managed resources can\'t memory leak, they can only waste resources for the current application and slow its garbage collection.  Unmanaged resources can leak, and <code>~Finalize</code> is best practice to ensure that they don\'t.</p>\n\n<p>In either case <code>using</code> is best practice.</p>\n'}, {'answer_id': 27637, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 2, 'selected': False, 'text': '<p>Complete explanation by Joe Duffy on "<a href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae" rel="nofollow noreferrer">Dispose, Finalization, and Resource Management</a>":</p>\n\n<blockquote>\n  <p>Earlier in the .NET Framework’s\n  lifetime, finalizers were consistently\n  referred to as destructors by C#\n  programmers. As we become smarter over\n  time, we are trying to come to terms\n  with the fact that the <strong>Dispose method\n  is really more equivalent to a C++\n  destructor (deterministic)</strong>, while the\n  <strong>finalizer is something entirely\n  separate (nondeterministic)</strong>. The fact\n  that C# borrowed the C++ destructor\n  syntax (i.e. ~T()) surely had at least\n  a little to do with the development of\n  this misnomer.</p>\n</blockquote>\n'}, {'answer_id': 36737, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 4, 'selected': False, 'text': '<p>The responses to this question have got more than a little confused.</p>\n\n<p>The title asks about disposal, but then says that they want memory back immediately.</p>\n\n<p>.Net is <em>managed</em>, which means that when you write .Net apps you don\'t need to worry about memory directly, the cost is that you don\'t have direct control over memory either.</p>\n\n<p>.Net decides when it\'s best to clean up and free memory, not you as the .Net coder.</p>\n\n<p>The <code>Dispose</code> is a way to tell .Net that you\'re done with something, but it won\'t actually free up the memory until it\'s the best time to do so.</p>\n\n<p>Basically .Net will actually collect the memory back when it\'s easiest for it to do so - it\'s very good at deciding when.  Unless you\'re writing something very memory intensive you normally don\'t need to overrule it (this is part of the reason games aren\'t often written in .Net yet - they need complete control)</p>\n\n<p>In .Net you can use <code>GC.Collect()</code> to force it to immediately, but that is almost always bad practise. If .Net hasn\'t cleaned it up yet that means it isn\'t a particularly good time for it to do so.</p>\n\n<p><code>GC.Collect()</code> picks up the objects that .Net identifies as done with. If you haven\'t disposed an object that needs it .Net may decide to keep that object. This means that <code>GC.Collect()</code> is only effective if you correctly implement your disposable instances.</p>\n\n<p><code>GC.Collect()</code> is <strong>not</strong> a replacement for correctly using IDisposable.</p>\n\n<p>So Dispose and memory are not directly related, but they don\'t need to be.  Correctly disposing will make your .Net apps more efficient and therefore use less memory though.</p>\n\n<hr>\n\n<p>99% of the time in .Net the following is best practice:</p>\n\n<p><strong>Rule 1:</strong> If you don\'t deal with anything <em>unmanaged</em> or that implements <code>IDisposable</code>  then don\'t worry about Dispose.</p>\n\n<p><strong>Rule 2:</strong> If you have a local variable that implements IDisposable make sure that you get rid of it in the current scope:</p>\n\n<pre><code>//using is best practice\nusing( SqlConnection con = new SqlConnection("my con str" ) )\n{\n    //do stuff\n} \n\n//this is what \'using\' actually compiles to:\nSqlConnection con = new SqlConnection("my con str" ) ;\ntry\n{\n    //do stuff\n}\nfinally\n{\n    con.Dispose();\n}\n</code></pre>\n\n<p><strong>Rule 3:</strong> If a class has a property or member variable that implements IDisposable then that class should implement IDisposable too. In that class\'s Dispose method you can also dispose of your IDisposable properties:</p>\n\n<pre><code>//rather basic example\npublic sealed MyClass :\n   IDisposable\n{   \n    //this connection is disposable\n    public SqlConnection MyConnection { get; set; }\n\n    //make sure this gets rid of it too\n    public Dispose() \n    {\n        //if we still have a connection dispose it\n        if( MyConnection != null )\n            MyConnection.Dispose();\n\n        //note that the connection might have already been disposed\n        //always write disposals so that they can be called again\n    }\n}\n</code></pre>\n\n<p>This isn\'t really complete, which is why the example is sealed. Inheriting classes may need to observe the next rule...</p>\n\n<p><strong>Rule 4:</strong> If a class uses an <em>unmanaged</em> resource then implement IDispose <em>and</em> add a finaliser.</p>\n\n<p>.Net can\'t do anything with the <em>unmanaged</em> resource, so now we are talking about memory. If you don\'t clean it up you can get a memory leak.</p>\n\n<p>The Dispose method needs to deal with both <em>managed</em> and <em>unmanaged</em> resources.</p>\n\n<p>The finaliser is a safety catch - it ensures that if someone else creates and instance of your class and fails to dispose it the \'dangerous\' <em>unmanaged</em> resources can still be cleaned up by .Net.</p>\n\n<pre><code>~MyClass()\n{\n    //calls a protected method \n    //the false tells this method\n    //not to bother with managed\n    //resources\n    this.Dispose(false);\n}\n\npublic void Dispose()\n{\n    //calls the same method\n    //passed true to tell it to\n    //clean up managed and unmanaged \n    this.Dispose(true);\n\n    //as dispose has been correctly\n    //called we don\'t need the \n\n    //\'backup\' finaliser\n    GC.SuppressFinalize(this);\n}\n</code></pre>\n\n<p>Finally this overload of Dispose that takes a boolean flag:</p>\n\n<pre><code>protected virtual void Dispose(bool disposing)\n{\n    //check this hasn\'t been called already\n    //remember that Dispose can be called again\n    if (!disposed)\n    {\n        //this is passed true in the regular Dispose\n        if (disposing)\n        {\n            // Dispose managed resources here.\n        }\n\n        //both regular Dispose and the finaliser\n        //will hit this code\n        // Dispose unmanaged resources here.\n    }\n\n    disposed = true;\n}\n</code></pre>\n\n<p>Note that once this is all in place other managed code creating an instance of your class can just treat it like any other IDisposable (Rules 2 and 3).</p>\n'}, {'answer_id': 36751, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 1, 'selected': False, 'text': '<p>@Keith,</p>\n\n<p>I agree with all of your rules except #4. Adding a finalizer should only be done under very specific circumstances. If a class uses unmanaged resources, those should be cleaned up in your Dispose(bool) function. This same function should only cleanup managed resources when bool is true. Adding a finalizer adds a complexity cost to using your object as each time you create a new instance it must also be placed on the finalization queue, which is checked each time the GC runs a collection cycle. Effectively, this means that your object survives one cycle/generation longer than it should so the finalizer can be run. The finalizer should not be thought of as a "safety net".</p>\n\n<p>The GC will only run a collection cycle when it determines that there is not enough available memory in the Gen0 heap to perform the next allocation, unless you "help" it by calling GC.Collect() to force an out-of-band collection.</p>\n\n<p>The bottom line is that, no matter what, the GC only knows how to release resources by calling the Dispose method (and possibly the finalizer if one is implemented). It is up to that method to "do the right thing" and clean up any unmanaged resources used and instruct any other managed resources to call their Dispose method. It is very efficient at what it does and can self-optimize to a large extent as long as it isn\'t helped by out-of-band collection cycles. That being said, short of calling GC.Collect explicitly you have no control over when and in what order objects will be disposed of and memory released.</p>\n'}, {'answer_id': 9832716, 'author': 'Jaycephus', 'author_id': 1287133, 'author_profile': 'https://Stackoverflow.com/users/1287133', 'pm_score': -1, 'selected': False, 'text': "<p>In answer to the original question, with the information given so far by the original poster, it is 100% certain that he does not know enough about programming in .NET to even be given the answer: use GC.Collect(). I would say it is 99.99% likely that he really doesn't need to use GC.Collect() at all, as most posters have pointed out. </p>\n\n<p>The correct answer boils down to 'Let the GC do its job. Period. You have other stuff to worry about. But you might want to consider whether and when you should dispose of or clean up specific objects, and whether you need to implement IDisposable and possibly Finalize in your class.'</p>\n\n<p>Regarding Keith's post and his Rule #4:</p>\n\n<p>Some posters are confusing rule 3 and rule 4. Keith's rule 4 is absolutely correct, unequivocately. It's the one rule of the four that needs no editing at all. I would slightly rephrase some of his other rules to make them clearer, but they are essentially correct if you parse them correctly, and actually read the whole post to see how he expands on them.</p>\n\n<ol>\n<li><p>If your class doesn't use an unmanaged resource AND it also never instantiates another object of a class that itself uses, directly or ultimately, an unmanaged object (i.e., a class that implements IDisposable), then there would be no need for your class to either implement IDisposable itself, or even call .dispose on anything. (In such a case, it is silly to think you actually NEED to immediately free up memory with a forced GC, anyway.)</p></li>\n<li><p>If your class uses an unmanaged resource, OR instantiates another object that itself implements IDisposable, then your class should either:</p>\n\n<p>a) dispose/release these immediately in a local context in which they were created, OR...</p>\n\n<p>b) implement IDisposable in the pattern recommended within Keith's post, or a few thousand places on the internet, or in literally about 300 books by now.</p>\n\n<p>b.1) Furthermore, if (b), and it is an unmanaged resource that has been opened, both IDisposable AND Finalize SHOULD ALWAYS be implemented, per Keith's Rule #4.<br>\nIn this context, Finalize absolutely IS a safety net in one sense: if someone instantiates YOUR IDisposable object that uses an unmanaged resource, and they fail to call dispose, then Finalize is the last chance for YOUR object to close the unmanaged resource properly.<br>\n(Finalize should do this by calling Dispose in such a way that the Dispose method skips over releasing anything BUT the unmanaged resource. Alternatively, if your object's Dispose method IS called properly by whatever instantiated your object, then it BOTH passes on the Dispose call to all IDisposable objects it has instantiated, AND releases the unmanaged resources properly, ending with a call to suppress the Finalize on your object, which means that the impact of using Finalize is reduced if your object is disposed properly by the caller. All of these points are included in Keith's post, BTW.)  </p>\n\n<p>b.2) IF your class is only implementing IDisposable because it needs to essentially pass on a Dispose to an IDisposable object it has instantiated, then don't implement a Finalize method in your class in that case. Finalize is for handling the case that BOTH Dispose was never called by whatever instantiated your object, AND an unmanaged resource was utilized that's still unreleased.  </p></li>\n</ol>\n\n<p>In short, regarding Keith's post, he is completely correct, and that post is the most correct and complete answer, in my opinion. He may use some short-hand statements that some find 'wrong' or object to, but his full post expands on the usage of Finalize completely, and he is absolutely correct. Be sure to read his post completely before jumping on one of the rules or preliminary statements in his post.</p>\n"}, {'answer_id': 10422450, 'author': 'Ashley Frieze', 'author_id': 1355930, 'author_profile': 'https://Stackoverflow.com/users/1355930', 'pm_score': 3, 'selected': False, 'text': '<p>I wrote a summary of Destructors and Dispose and Garbage collection on <a href="http://codingcraftsman.wordpress.com/2012/04/25/to-dispose-or-not-to-dispose/" rel="noreferrer">http://codingcraftsman.wordpress.com/2012/04/25/to-dispose-or-not-to-dispose/</a></p>\n\n<p>To answer the original question:</p>\n\n<ol>\n<li>Don\'t try to manage your memory</li>\n<li>Dispose is not about memory management, it\'s about unmanaged resource management</li>\n<li>Finalizers are an innate part of the Dispose pattern and actually slow down memory freeing of managed objects (as they have to go into the Finalization queue unless already Dispose d)</li>\n<li>GC.Collect is bad as it makes some short-lived objects appear to be required for longer and so slows them down from being collected.</li>\n</ol>\n\n<p>However, GC.Collect could be useful if you had a performance critical section of code and wanted to reduce the likelihood of Garbage Collection slowing it down. You call that before.</p>\n\n<p>On top of that, there is an argument in favour of this pattern:</p>\n\n<pre><code>var myBigObject = new MyBigObject(1);\n// something happens\nmyBigObject = new MyBigObject(2);\n// at the above line, there are temporarily two big objects in memory and neither can be collected\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>myBigObject = null; // so it could now be collected\nmyBigObject = new MyBigObject(2);\n</code></pre>\n\n<p>But the main answer is that Garbage Collection just works unless you mess around with it!</p>\n'}]
['https://Stackoverflow.com/questions/12368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1271/']