C# - closing Sql objects best practice

前端 未结 8 1025
陌清茗
陌清茗 2020-12-31 11:29

If you have a C# function with Sqlaccess, is it mandatory to close all objects/handles, or is everything cleaned up automatically once you exit the function

For exam

8条回答
  •  失恋的感觉
    2020-12-31 12:06

    Explicit disposing in the finally statement is another approach, although the using statement is a much better solution. It produces a bit more code, but demonstrates the goal...

    SqlConnection conn = null;
    try
    {
        //create connection
    
        SqlCommand cmd = null;
        try
        {
            //create command
    
            SqlDataReader reader = null;
            try 
            {
                //create reader
            }
            finally
            {
                reader.Dispose();
            }
        }
        finally
        {
            cmd.Dispose();
        }
    }
    finally 
    {
        conn.Dispose();
    }
    

提交回复
热议问题