为什么我永远得不到 ObjectDisposedException?

Why do I never get the 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();
    }  

我希望在离开 using 街区后得到 ObjectDisposedException

访问 _myTimer.Interval 一直工作到程序结束。另外,我可以随时打电话给 _myTimer.Dispose()。即使等待 GarbageCollector 也无助于获得 ObjectDisposedException.

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

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

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