garbage collection - C# disposable question -


would garbage collector automatically free unmanaged resources (whatever, actually) associated idisposable instance if, example, forgot write using statement?

obviously, don't know when happen, fine leave idisposable gc when don't care resources , i'm fine disposed eventually?

would garbage collector automatically free unmanaged resources (whatever, actually) associated idisposable instance if, example, forgot write using statement?

usually, not necessarily. author of disposable resource needs right thing.

obviously, don't know when happen, fine leave idisposable gc when don't care resources , i'm fine disposed eventually?

your question presupposes falsehood. the garbage collector never calls dispose, ever. rather, garbage collector calls destructor (or "finalizer" if prefer). destructor might or might not call dispose forgetful user.

your question indicates bad attitude. you might not care if resources freed late program might care! if customer running two programs both try access same unmanaged resource, 1 written , 1 written else? be citizen; release scarce resources done them other programs can use them. that's real purpose of "using" -- it's polite ensuring scarce resources reclaimed quickly.

a correct implementation of dispose pattern ensure destructor cleans unmanaged resources if user forgets call dispose, , ensure destructor not clean resources if remember.

if person writing implementation of dispose class owns unmanaged resources it responsibility destructor code right case user not call dispose correctly. correct way write code extremely documented; follow pattern. see jon's comments helpful links.

note if writing such class required make work in scenarios in impossible user call dispose. example, suppose constructor allocates 2 unmanaged resources, , between allocation of first , second, exception thrown , caught outside of constructor. there's no way user ever call dispose because assignment of new object reference happens after constructor runs successfully, , constructor never finished running successfully. how first unmanaged resource freed? destructor can free it. destructor has robust in face of such scenarios; object destructed might never have been constructed cannot rely on invariant of constructor.


Comments