ror*_*.ap 2 .net c# idisposable exception using-statement
我从像许多来源理解这个和这个,该Dispose的方法IDisposable如果有异常被抛出总是被称为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");
}
}
Run Code Online (Sandbox Code Playgroud)
当抛出未处理的异常时,它退出应用程序.Dispose永远不会调用该方法.为什么?
Ham*_*jam 11
Environment.Exit将终止该程序
如果从try或finally块调用Exit,则任何catch块中的代码都不会执行.如果使用return语句,catch块中的代码会执行.
using (var x = new Disposable())
{
throw new Exception("asdfsdf");
}
Run Code Online (Sandbox Code Playgroud)
将被转换为
Disposable x = new Disposable();
try
{
throw new Exception("asdfsdf");
}
finally
{
if (x != null)
x.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
581 次 |
| 最近记录: |