微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么我永远不会得到 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。