This post originated from an RSS feed registered with .NET Buzz
by Brad Wilson.
Original Post: Using Console Safe in a Finalizer
Feed Title: The .NET Guy
Feed URL: /error.aspx?aspxerrorpath=/dotnetguy/Rss.aspx
Feed Description: A personal blog about technology in general, .NET in specific, and when all else fails, the real world.
There’s a general rule which says: never touch any managed reference-type object from within your finalizer. The rationale behind that idea is that you don’t whether the thing you’re touching had already been collected and finalized, thus making it unusable. This is even true for static objects, since you could be in the middle of shutdown.
Back during the implementation of V1.0, I was debugging a problem where a finalizer didn’t seem to be called. To help figure out if the finalizer was running at all, I added a call to Console.WriteLine inside it, but then my app started blowing up with an unhandled ObjectDisposedException. How could simply adding a call to Console.WriteLine to the finalizer break the app?
The problem turned out to be that the underlying console stream was being finalized before my instance. The lesson I learned was to follow this guideline: only use non-finalizable instance data from your own finalizer. But I also happened to own the code for the Console class, so I special cased Console.WriteLine—now we never close the handles for stdout, stdin, or stderr. This is somewhat useful for printf-style debugging and logging, and turned out later to be required to support multiple appdomains within the same process (i.e. you don’t want arbitrary appdomains closing your process-wide handle for stdout). So bottom line: using Console from your finalizer is actually a safe thing to do, but watch out for everything else.
The opinions expressed herein are solely those of Brad Wilson, and not meant as an endorsement of or by any other individuals or groups. This syndication is provided for the private, personal use of individuals. Unauthorized commercial reproduction is strictly prohibited.