BeginExecuteNonQuery without EndExecuteNonQuery

后端 未结 5 1442
梦谈多话
梦谈多话 2020-12-03 10:40

I have the following code:

using (SqlConnection sqlConnection = new SqlConnection(\"blahblah;Asynchronous Processing=true;\")
{
    using (SqlCommand command         


        
5条回答
  •  生来不讨喜
    2020-12-03 11:03

    In this case the using statements won't be necessary because you should manually close it yourself rather than allowing the syntactic sugar dispose it for you (i.e. at the }). It should be as simple as this to ensure you don't have leaks.

        using (SqlConnection sqlConnection = new SqlConnection("blahblah;Asynchronous Processing=true;")
        {
            using (SqlCommand command = new SqlCommand("someProcedureName", sqlConnection))
            {
                sqlConnection.Open();
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@param1", param1);
                command.BeginExecuteNonQuery((ar) =>
                {
                    var cmd = (SqlCommand)ar.AsyncState;
                    cmd.EndExecuteNonQuery(ar);
                    cmd.Connection.Close();
                }, command);
            }
        }
    
    As you can see the lambda expression that is fired once the command is finished (no matter how long it takes) will do all the closing for you.

提交回复
热议问题