Alex Rivera | Logout

BeginExecuteNonQuery without EndExecuteNonQuery

Asked 2009-10-09T16:49:21.763
20

I have the following code:

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();
    }
}

I never call EndExecuteNonQuery.

Two questions, first will this block because of the using statements or any other reason? Second, will it break anything? Like leaks or connection problems? I just want to tell sql server to run a stored procedure, but I don't want to wait for it and I don't even care if it works. Is that possible? Thanks for reading.

Edit
Report

2 Answers

26

This won't work because you're closing the connection while the query is still running. The best way to do this would be to use the threadpool, like this:

ThreadPool.QueueUserWorkItem(delegate {
    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.ExecuteNonQuery();
        }
    }
});

In general, when you call Begin_Whatever_, you usually must call End_Whatever_ or you'll leak memory. The big exception to this rule is Control.BeginInvoke.

answered 2009-10-09T16:52:45.767
5

You should always call the EndExecuteNonQuery() method to prevent leaks. It may work now but who knows what will happen in future versions of .NET. The general rule is always follow a BeginExecute... with an EndExecute...

answered 2009-10-09T16:53:42.160

Your Answer