为什么使用不在调试器中调用dispose方法

时间:2018-03-05 09:20:53

标签: c#

我有这个测试代码。 为什么在使用语句中引发异常时不调用dispose方法? According to the documentation应该调用它。

using System;
using System.IO;
using System.Text;

namespace UsingTest {
    class Program {
    public class MyClass : IDisposable
    {
        private bool disposed = false;

        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(bool disposing) {
            if (!disposed) {
                if (disposing) {
                    using (var f = new FileStream("log.txt", FileMode.Create)) {
                        var msg = "MyClass disposed";
                        f.Write(Encoding.UTF8.GetBytes(msg), 0, Encoding.UTF8.GetByteCount(msg));
                    }
                }
                disposed = true;
            }
        }

        ~MyClass() {
            Dispose(false);
        }
    }

    static void Main(string[] args) {
        using (var c = new MyClass()) {
            Console.WriteLine("some work");
            throw new Exception("Exception");
            Console.WriteLine("Hello World!");
        }
    }
}
}

感谢。

1 个答案:

答案 0 :(得分:3)

static void Main(string[] args) {

        using (var c = new MyClass()) {
            Console.WriteLine("some work");
            throw new Exception("Exception");
            Console.WriteLine("Hello World!");
        }

    }

这是创建MyClass的新实例 在实例化时,它会写入控制台。然后抛出异常。 异常时,调试器会介入,并尝试帮助您调试代码。 Visual Studio中的调试器将继续运行您的代码足够长的时间 - 调试它。

if you will run it from Visual Studio with debugger - it will not be called

在调试器停止运行/监听代码后,方法(Dispose)被称为

由于调试器不再存在,因此Dispose中的断点不会被命中。 代码未运行,因为运行时已退出(按Visual Studio的顺序确定您现在已完成)

如果你在没有调试的情况下运行它(ctrl + f5),你也会看到创建的文件。

尝试将System.Diagnostics.Debugger.Launch();置于Dispose方法中,如下所示:

public void Dispose(bool disposing) {
    System.Diagnostics.Debugger.Launch();
    //etc
}

这将在那个时间点附加调试器。