Do IDisposable objects get disposed of if the program is shut down unexpectedly?

前端 未结 6 1692
借酒劲吻你
借酒劲吻你 2021-01-17 07:31

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

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 07:57

    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:

    1. Everybody thinks about garbage collection the wrong way (Raymond Chen)
    2. When everything you know is wrong, part one (Eric Lippert)
    3. When everything you know is wrong, part two (Eric Lippert)
    4. Terminating a Process (MSDN)

提交回复
热议问题