WriteLine() and Exit()

  • Thread starter Thread starter Michi Henning
  • Start date Start date
M

Michi Henning

Hi, I couldn't find an answer to this question in the spec, so
I'd appreciate some insight.

Here's a simple class:

class SimpleClass
{
//...

~SimpleClass()
{
System.Console.WriteLine("~SimpleClass");
}
}

Let's say I've created lots of these objects over time and
orphaned them, so they become eligible for GC. (I'm doing this
in a multi-threaded environment, so many threads may have created
such objects.) Then (after joining with all outstanding threads)
the main thread calls System.Environment.Exit().

The GC may kick in halfway through that call. The question is:
is it guaranteed that the WriteLine() call in the destructor
of SimpleClass() will always work? I can't find a guarantee to
that effect in the spec. What I'm worried about is that, during
Exit(), by the time ~SimpleClass() is called by the GC,
the I/O subsystem may have been partly dismantled already,
so the WriteLine() could be lost or potentially cause a crash.

Thanks,

Michi.
 
Hi,

You are right, you should never put that code on the finalizer, you should
call the Dispose method of your class and ask if the object has been disposed.

Btw, is a bad practice to use a finalizer if you don't use unmanaged code,
the main reason is what you are stating :)

Best regards
Salva
 
Back
Top