Does Dispose still get called when exception is thrown inside of a using statement?

前端 未结 3 609
广开言路
广开言路 2020-11-28 08:46

In the example below, is the connection going to close and disposed when an exception is thrown if it is within a using statement?

using (var co         


        
3条回答
  •  攒了一身酷
    2020-11-28 09:26

    This is how reflector decodes the IL generated by your code:

    private static void Main(string[] args)
    {
        SqlConnection conn = new SqlConnection("...");
        try
        {
            conn.Open();
            DoStuff();
        }
        finally
        {
            if (conn != null)
            {
                conn.Dispose();
            }
        }
    }
    
    

    So the answer is yes, it will close the connection if

    DoStuff()
    throws an exception.

提交回复
热议问题