Note that there are some explanatory texts on larger screens.

plurals
  1. POSpecific questions about C# Dispose Pattern
    text
    copied!<p>I have a few basic questions about the Dispose Pattern in C#.</p> <p>In the following code snippet, which seems to be a standard way of implementing the dispose pattern, you’ll notice that managed resources are not handled if disposing is false. How/when are they handled? Does the GC come along and handle the managed resources later? But if that’s the case, what does the GG.SuppressFinalize(this) call do? Can someone give me an example of disposing of managed resources? Unhooking events comes to mind. Anything else? The way the pattern is written, it seems they would get disposed (later) if you did nothing in the “if (disposing)” section. Comments?</p> <pre><code>protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // Dispose managed resources. } // There are no unmanaged resources to release, but // if we add them, they need to be released here. } disposed = true; // If it is available, make the call to the // base class's Dispose(Boolean) method base.Dispose(disposing); } // implements IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } </code></pre> <p>Is it true what I read about locks in Dispose(bool) in this thread, <a href="https://stackoverflow.com/questions/1196203/how-do-i-implement-the-dispose-pattern-in-c-when-wrapping-an-interop-com-object">How do I implement the dispose pattern in c# when wrapping an Interop COM Object?</a>? It says, “Meta-meta comment - as well as that, it's important that you never acquire locks or use locking during your unmanaged cleanup.” Why is that? Does it apply to unmanaged resources as well?</p> <p>Finally, does on ever implement a finalizer (~MyClass() in C#) without implementing IDisposable? I believe I read somewhere that finalizers and IDisposable are not necessary (or desirable) if there are no unmanaged resources. However, I do see the use of a finalizer without IDisposable in some examples (see: <a href="http://www.codeproject.com/KB/cs/idisposable.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/idisposable.aspx</a> as one example) Thanks, Dave</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload