more geeky dot net stuff: cordbg, finalize, garbage collection
so at work i do my dotnet programming with ultraedit and the framework. i compile with csc. and now i debug with cordbg, the 'common language runtime test debugger shell' that comes with the sdk. it is quite...er...interesting? seriously, this debugger allows you to drop down into the actual il if you feel like it to see what is really going on.
it drives home the whole finalize thing and the garbage collection (gc) thing. try it. step through your program and watch while it stops at each close } to do the requisite gc. if you add destructors to your objects though, don't expect to see that code run while you are stepping through the code.
why? where does gc occur? in a separate thread! yes, all of your finalize methods occur in a completely different thread of execution than your main program.
so the 'finalize' method is just like a java/c++ destructor right? no! the finalize is not a destructor. it is code scheduled to run at some point. it is only guaranteed to run if you call gc.waitforpendingfinalizers(). if you don't make that call, the system can be shutdown prior to your finalize completing. (ok, pulling the power cable isn't fair.) what happens is this:
- object goes out of scope
- object is checked for any existing (strong) references, if none exist it is marked for deletion and it's finalize method (if it exists) is placed into the finalize que.
- the framework goes through the list and executes the finalize methods when it feels like it so you should always include and rely on a finalize for cleanup and call
gc.waitforpendingfinalizers(), right? wrong! close or dispose are much preferred to finalize as a cleanup mechanism.
- always include a finalize?
yes.
- rely on it to do your cleanup?
no.
- 'but if i make my own dispose method won't finalize be called anyway?'
not if you call gc.suppressfinalize(this) at some point in your dispose method. this will cause the gc to not place a reference to the finalize method into the finalize que.
read about it on the msdn site:
garbage collection: automatic memory management in the microsoft .net framework part one, and part two.
|
|