Search code examples
c#console-applicationidisposable

Calling Environment.Exit() Within a Using Block


If I have a console application with code like:

using (DisposableObject object = new DisposableObject())
{
   if (a condition)
     Environment.Exit(0);

   // Do Stuff
}

Will my object be properly disposed? Or does the thread die before the object is cleaned up?


Solution

  • Your application will terminate and all managed memory will be released at that point.

    The generated finally block will not execute, so any Dispose methods will not be called, so any non-managed resources may very well not be released.

    See Don't Blindly Count on a Finalizer.