Note that there are some explanatory texts on larger screens.

plurals
  1. POAbout the Dispose pattern and the Finalizer in C#
    text
    copied!<p>First in <a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e%28v=vs.100%29.aspx" rel="nofollow">this MSDN page</a></p> <p>there is a standard Dispose pattern. And there is a bool as the parameter of the protected <code>Dispose</code> method to tell the GC whether managed resources are freed manually already, so that the GC does not need to care about them. </p> <p>Now the question is, what exactly should be done inside the <code>if (disposing) {}</code> block? Normally the GC cleans up managed resources, so one doesn't need to do anything special. But since inside this block, one needs to explicitly clean up managed resources, does that mean one just set all the fields and stuff in the object to <code>null</code>? </p> <p>Second, isn't it just nicer to have just one destructor (or finalizer whatever it calls) in the language? And then in the GC design, just put a bit to determine if the destructor is already called so that there is no need to garbage collect it, or the destructor is not yet called and the GC should clean it up. I found the Dispose pattern quite complicated, and I am very confused what to clean up in which function and how to clean up in derived classed. And by using a signle destructor design, the GC just cleans things up when they are not cleaned up yet, and does not clean up when they are already. </p> <p>Greetings</p> <p>PS: So is this also a good and simpler pattern to clean up objects?</p> <pre><code>class Foo { bool unmanagedDisposed = false; void Dispose() {/*clean up unmanaged resources*/ unmanagedDisposed = true;} ~Foo() {if (!unmanagedDisposed) Dispose();} } </code></pre> <p>So if the programmer knows and remembers to call <code>Dispose()</code>, nothing to do in the finalizer, otherwise clean up unmanaged resources in the finalizer. And here we don't need to care about those managed resources.</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