class Program
{
static void Main(string[] args)
{
try
{
using (TestUsing test = new TestUsing())
{
throw new Exception("异常");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine();
using (TestUsing test = new TestUsing())
{
Console.WriteLine("执行业务代码");
return;
}
Console.WriteLine("执行结束");
Console.ReadKey();
}
}
class TestUsing : IDisposable
{
public void Dispose()
{
Console.WriteLine("被释放了");
Console.ReadKey();
}
}
执行结果:
结论:
1、在using自动释放资源时,无论是return还是异常中断,dispose方法都会被执行
2、dispose方法在using块结束的时候就会被执行,在catch异常之前