为什么我永远不会得到 ObjectDisposedException?

问题描述

我的测试方法如下:

private static System.Timers.Timer _myTimer;

static void Main(string[] args)
    {
        using (_myTimer = new System.Timers.Timer(1000))
        {
            _myTimer.Elapsed += (o,e) => Console.WriteLine($"timer elapsed");
            _myTimer.AutoReset = true;
            _myTimer.Enabled = true;
            Thread.Sleep(4000); // let the timer fire a couple of times
        } // dispose timer?

        Thread.Sleep(2000); // timer won't fire here
        try
        {
            Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // this won't throw an ObjectdisposedException on _myTimer
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex}");
        }

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        try
        {
            Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // still no ObjectdisposedException
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex}");
        }

        try
        {
            //_myTimer.Start(); // throws the ObjectdisposedException
            _myTimer.dispose(); // does not throw the ObjectdisposedException
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex}");
        }            

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        try
        {
            Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // still no ObjectdisposedException
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex}");
        }

        Console.WriteLine("Press any key to continue...");
        Console.ReadLine();
    }  

我希望在离开 ObjectdisposedException 块后获得 using

访问 _myTimer.Interval 一直到程序结束。此外,我可以随时致电 _myTimer.dispose()。即使等待 GarbageCollector 也无助于获得 ObjectdisposedException

但是,如果我在离开 ObjectdisposedException 块后调用 _myTimer.Start(),我确实会得到 using

_myTimer 如何在我的程序的整个生命周期中都存在?

解决方法

调用 Dispose 不会删除对象或对它的引用。只要有对它的引用,它就不会被 GC。 Dispose 释放对象内的非托管资源,这可能但绝不保证至少会导致其某些方法停止工作并开始抛出 ObjectDisposedException

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...