Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Finalizers are a pain, and you should avoid them being <em>called</em> if possible. <em>However</em> if you are implemented IDisposable, you will almost always want to write one (in conjunction with a Dispose(bool) method). That calls Dispose(false) and GC.SuppressFinalize().</p> <p>If you don't implement a finalizer, then unless any IDisposable instances that you are holding implement finalizers correctly, you will leak. Say for example that SafeHandle didn't have a finalizer but relied on someone calling Dispose? If you held one, and didn't implement a finalizer, then you're allowing your consumer to permanently leak the handle by not calling Dispose on you!</p> <p>Assuming that both your consumer and objects that you consume will play nice isn't a reason not to play nice yourself.</p> <p>In addition, even if you use a SafeHandle, you should Dispose of it as if it were managed object. Otherwise if you don't dispose of it at all then it will have to wait until GC to be released, and if you do Dispose of it in Dispose but no a finalizer, and no one disposes of you, then it will have to wait until the GC after the one that collected you.</p> <p>b_richardson above has the right pattern, it's not hard, and by adding GC.SuppressFinalize() you avoid the two-pass GC except in cases where no on disposed of you properly. </p> <p>As for adding a boolean to track if we've been Disposed of yet, that'll work, I prefer to just write my Dispose methods to be rerunnable(check for null, etc.) also helps to do it that way when an object may acquire resources during use and you only want to dispose the ones it has.</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