Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

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

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

I know that using is the same as try / finally where it disposes of the object in the finally no matter what happens in the try. If I have a method that returns a value inside the using, even though execution leaves the method when it returns, does it still call .Dispose() on my object before/during/after it's returning?

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

Update: The accepted answer is the one I think best answers my question but note that this answer caught the stupidity of this code, that I'm returning a command that uses a disposed connection! :P

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<SqlCommand> 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...
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...