我从很多来源了解到this and this那Dispose
的方法IDisposable
如果在 a 中抛出异常,则始终会被调用Using
堵塞。那么我有这个代码:
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
方法从未被调用。为什么?
环境.退出将终止程序
如果从 try 或 catch 块中调用 Exit,则任何 finally 中的代码
块不执行。如果使用return语句,则代码中
finally 块确实执行。
using (var x = new Disposable())
{
throw new Exception("asdfsdf");
}
将被转换为
Disposable x = new Disposable();
try
{
throw new Exception("asdfsdf");
}
finally
{
if (x != null)
x.Dispose();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)