IDisposable.Dispose永远不会在使用块后发生异常后调用 [英] IDisposable.Dispose is never called after exception in using block

查看:224
本文介绍了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?

推荐答案

Environment.Exit 将终止程序


如果从try或catch块中调用Exit,则任何最终
块中的代码都不会执行。如果使用return语句,则
finally块中的代码会执行。

If Exit is called from a try or catch block, the code in any finally block does not execute. If the return statement is used, the code in the finally block does execute.



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永远不会在使用块后发生异常后调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆