c# - Why does this variable need to be set to null after the object is disposed? -
the documentation on powershell here has following interesting comment in it:
powershell powershell = powershell.create(); using (powershell) { //... } // after disposing of powershell object, still // need set powershell variable null // garbage collector can clean up. powershell = null; why powershell need set null after being disposed?
it's not directly powershell issue. when using block terminates, specified object(s) have dispose() methods called. these typically cleanup operations, avoid leaking memory , forth. however, dispose() doesn't delete object. if reference still exists outside using block (as in example), object still in scope. can't garbage-collected because there's still reference it, it's still taking memory.
what they're doing in example dropping reference. when powershell set null, powershell object pointing orphaned, since there no other variables referring it. once garbage collector figures out, can free memory. happen @ end of method anyway (because powershell go out of scope), way system resources little sooner.
(edit: brian rasmussen points out, .net runtime extremely clever garbage collection. once reaches last reference powershell in code, runtime should detect don't need anymore , release garbage collection. powershell = null; line isn't doing anything.)
by way, pattern looks strange me. usual approach this:
using (powershell powershell = powershell.create()) { //... } this way, powershell goes out of scope @ end of using block, right after it's disposed. it's easier tell variable relevant, , save code because don't need powershell = null line anymore. i'd better coding practice, because powershell never exists in already-disposed state. if modifies original code , tries use powershell outside using block, whatever happens bad.
Comments
Post a Comment