asp.net - C# Singleton Log Class that Stores Messages on Disk On Destruction -
i have asp.net c# singleton (scoped session through httpcontext.current.session) receives messages code (warnings, errors, exceptions etc.). messages related code problems, used while debugging, not during production.
i wrote custom destructor object contents written/appended file on disk.
i wanted ask 2 things related situation:
a] is idea open file , write during object destructor? concurrency io access handled through static lock.
b] when destructor called session scoped objects? when session expired on server?
i recommend using existing logging package. if decide yourself, , bare in mind future:
a) no it's not idea. shouldn't access managed resources in finalizer (destructor), if have log strings in memory example, it's bad practice access them (or list contained in) may have been finalized @ point.
i don't want repeat recommended pattern, see https://stackoverflow.com/a/1943856/2586804
you'll see there 1 place should access managed during dispose
, if called user code , not gc. should come conclusion achieve this, must call .dispose()
(or using using
) when (and if) gc it, cannot access managed members contain log lines.
b) don't know, doesn't matter cannot use finalizer purpose anyway.
the bottom line can't rely on gc run code you. it's bad practice because don't know when it's going happen, plus reference object anywhere, or in future prevent object being collected , introduce bug.
you shouldn't c# finalizers/destructors run code because that's not for, freeing unmanaged resources machine doesn't run out. , note, it's rare occurrence use them in c# because peoples day-to-day work managed objects.
instead explicitly tell object write it's logs, method called flush
name. or let write 1 line @ time. usual behaviour.
Comments
Post a Comment