本文介绍了IDisposable.Dispose永远不会在使用块后发生异常后调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从诸如和,如果在 IDisposable 中的 Dispose 方法将始终被调用, 使用块。因此,我得到了以下代码:

I understand from many sources like this and this that the Dispose method of an IDisposable will always be called if an exception is thrown in a Using block. So then I have this code:

static class MainEntryPoint
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += HandleUnhandledException;

        using (var x = new Disposable())
        {
            throw new Exception("asdfsdf");
        }
    }

    private static void HandleUnhandledException(Object sender, System.UnhandledExceptionEventArgs e)
    {
        Environment.Exit(0);
    }
}

class Disposable : IDisposable
{
    public void Dispose()
    {
        System.Diagnostics.Debug.Print("I am disposed");
    }
}

当未处理的异常为抛出。永远不会调用 Dispose 方法。为什么?

It exits the application when an un-handled exception is thrown. The Dispose method is never called. Why?

推荐答案

将终止程序



using (var x = new Disposable())
{
    throw new Exception("asdfsdf");
}

将转换为

Disposable x = new Disposable();
try
{
    throw new Exception("asdfsdf");
}
finally
{
    if (x != null)
        x.Dispose();
}

这篇关于IDisposable.Dispose永远不会在使用块后发生异常后调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:32
查看更多