使用using语句实际上生成的IL代码中是一个try, finally代码块,在finally代码块里释放资源。
比如这样一段代码:
using (SqlConnection conn = new SqlConnection())
{
conn.Open();
throw new Exception("Exception!!");//抛出异常之后能回收SqlConnection对象的资源吗?
}
IL代码可为:
// Code size 42 (0x2a)
.maxstack 2
.locals init ([0] class [System.Data]System.Data.SqlClient.SqlConnection conn,
[1] bool CS$4$0000)
IL_0000: nop
IL_0001: newobj instance void [System.Data]System.Data.SqlClient.SqlConnection::.ctor()
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: ldloc.0
IL_0009: callvirt instance void [System.Data]System.Data.Common.DbConnection::Open()
IL_000e: nop
IL_000f: ldstr "Exception!!"
IL_0014: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0019: throw
} // end .try
finally
{
IL_001a: ldloc.0
IL_001b: ldnull
IL_001c: ceq
IL_001e: stloc.1
IL_001f: ldloc.1
IL_0020: brtrue.s IL_0029
IL_0022: ldloc.0
IL_0023: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0028: nop
IL_0029: endfinally
} // end handler
可以看到调用了SqlConnection的Dispose方法释放了资源。