What happens if the program exits unexpectedly (either by exception or the process is terminated)? Are there any situations like this (or otherwise) where the program will t
In addition to Patrick Hofman's and Alexei's answer cleanup may be not performed even if the application terminates correctly.
As you probably know the Dispose
method is not called when the garbage collector collects the object which implements IDisposable
interface. But the GC will call the Finalize
method also known as finalizer. In it you should write your cleanup logic using Dispose Pattern. And yes, the .Net Framework will try to run all finalizers, but there is no guaranty that they ever be executed.
As an example, the program bellow has the very long running finalizer. Therefore, the .Net will terminate the process and you will never see the message.
class FinalizableObject
{
~FinalizableObject()
{
Thread.Sleep(50000);
Console.WriteLine("Finalized");
}
}
class Program
{
static void Main(string[] args)
{
new FinalizableObject();
}
}
This can be caused by any long running operation like releasing a network handle or something else which will require much time.
Therefore, you should never rely on finalizers and disposable objects. But all opened handles to kernel objects will be closed automatically, so you should not worry about them.
I will recommend you to read few interesting articles about finalizers and the GC in addition to the answers: