开发者

basic about "using" construct

If I use "using" construct, I know that the object gets automatically disposed. What happens if a statement inside an "using" construct raises an exception. Is the "using" object still disposed? If 开发者_开发技巧so, when?


A using block is converted - by the compiler - to this:

DisposableType yourObj = new DisposableType();
try
{
    //contents of using block
}
finally
{
    ((IDisposable)yourObj).Dispose();
}

By putting the Dispose() call in the finally block, it ensures Dispose is always called - unless of course the exception occurs at the instantiation site, since that happens outside the try.

It is important to remember that using is not a special kind of operator or construct - it's just something the compiler replaces with something else that's slightly more obtuse.


This article explains it nicely.

Internally, this bad boy generates a try / finally around the object being allocated and calls Dispose() for you. It saves you the hassle of manually creating the try / finally block and calling Dispose().


Actually Using block is Equivalent to try - finally block, Which ensures that finally will always execute e.g.

using (SqlConnection con = new SqlConnection(ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand("Command", con))
    {
        con.Open();
        cmd.ExecuteNonQuery();
    }
}

Equals to

SqlConnection con =  null;
SqlCommand cmd = null;

try
{
    con = new SqlConnection(ConnectionString);
    cmd = new SqlCommand("Command", con);
    con.Open();
    cmd.ExecuteNonQuery();
}
finally
{
    if (null != cmd);
        cmd.Dispose();
    if (null != con)
        con.Dispose();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜