If I return a value inside a using block in a method, does the using dispose of the object before the return?

前端 未结 2 444
走了就别回头了
走了就别回头了 2020-12-11 08:03

I\'m going through some old C#.NET code in an ASP.NET application making sure that all SqlConnections are wrapped in using blocks.

2条回答
  •  死守一世寂寞
    2020-12-11 08:54

    Yes. It will dispose of your object. This will actually cause a problem in your code, since the SqlCommand being returned is dependent on the SqlConnection, which will be Disposed of prior to the control flow returning to your caller.

    You can, however, use delegates to work around this. A good pattern to handle this is to rewrite your method like so:

    public static SqlCommand ProcessSqlCommand(string strSql, string strConnect, Action processingMethod)
    { 
        using (SqlConnection con = new SqlConnection(strConnect)) 
        { 
            con.Open(); 
            SqlCommand cmd = GetSqlCommand(); 
            cmd.Connection = con; 
            cmd.CommandText = strSql; 
            processingMethod(cmd); 
        } 
    } 
    

    You can then call this like:

    ProcessSqlCommand(sqlStr, connectStr, (cmd) =>
        {
            // Process the cmd results here...
        });
    

提交回复
热议问题