public SiteMsg GetMsg(SiteMsg msg)
{
using (SpaceDbContext context = new SpaceDbContext())
{
SiteMsg ret = new SiteMsg();
ret = (from m in context.SiteMsgs
where m.id == msg.id
select m).First();
return ret;
}
}
上边SpaceDbContext是一个EntityFramework的实体,类似于数据库资源
使用using语句可以自动释放资源,但是这里还没有出using语句块就直接return了,请问数据库资源有没有释放?
我们需知using 语句提供的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。
public bool TestMethod()
{
using (SqlConnection conn = new SqlConnection(""))
{
conn.Open();
return false;
}
}
IL代码如下 :
.method public hidebysig instance bool TestMethod() cil managed
{
// Code size 43 (0x2b)
.maxstack 2
.locals init ([0] class [System.Data]System.Data.SqlClient.SqlConnection conn,
[1] bool CS$1$0000,
[2] bool CS$4$0001)
IL_0000: nop
IL_0001: ldstr ""
IL_0006: newobj instance void [System.Data]System.Data.SqlClient.SqlConnection::.ctor(string)
IL_000b: stloc.0
.try
{
IL_000c: nop
IL_000d: ldloc.0
IL_000e: callvirt instance void [System.Data]System.Data.Common.DbConnection::Open()
IL_0013: nop
IL_0014: ldc.i4.0
IL_0015: stloc.1
IL_0016: leave.s IL_0028
} // end .try
finally
{
IL_0018: ldloc.0
IL_0019: ldnull
IL_001a: ceq
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brtrue.s IL_0027
IL_0020: ldloc.0
IL_0021: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0026: nop
IL_0027: endfinally
} // end handler
IL_0028: nop
IL_0029: ldloc.1
IL_002a: ret
} // end of method Class1::TestMethod