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?
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.
Resources that the operating system knows about will generally be cleaned up when an application exits. Resources that the operating system does not know about will generally not be cleaned up.
For example, some programs which uses a database and need to implement a locking paradigm which is different from anything the database server supports directly may use one or more "LockedResources" tables to keep track of what resources should be locked. Code which needs to acquire a resource will lock the "LockedResources" table, update it to show what resources need to be locked, and then release it; that operation on the "LockedResource" table will generally be quite quick (so the "LockedResource" table will locked only briefly), even if the application needs to hold the real resource for a long time. If, however, the application does an Environment.Exit
while the "LockedResources" table says it owns a resource, the operating system will have no clue how to update the "LockedResources" table to cancel such ownership.
In general, things like database applications should be designed to be robust even if a client application unexpectedly dies. For example, there could be a table of active clients, with each active client holding a lock on a record which identifies itself. If a client that wants to use a resource notices that "LockedResources" table has it checked out to some other client, the former client could check to ensure that the latter client's entry in the "active clients" table is still locked. If not, it could figure that the client in question has died and take appropriate action (recognizing that the client that died might have left its resource in a bad state). On the other hand, the fact that database should be designed to be robust if clients die unexpectedly doesn't mean they always are. Resource abandonment is not a good thing, even if it is usually survivable.