C# – Close connection when using a Transaction

asp.netasp.net-mvcctransactions

I have the following method which uses a transaction.

private string getDocumentDetailsByNumber(string DocNumber)
    {
       SqlTransaction transaction = DALDBConnection.SqlConnection.BeginTransaction();

            try
            {
                DataSet DocNum = new DataSet();

                string sDocNumber = "";
                string[] taleNamesDoc = new string[1];
                taleNamesDoc[0] = "docnumber";
                SqlParameter[] paramDoc = new SqlParameter[1];
                paramDoc[0] = new SqlParameter("@DocumentNumber", DocNumber.ToString().Trim());

                SqlHelper.FillDataset(transaction, CommandType.StoredProcedure, "spGetDocumentDetailsByNumber", DocNum, taleNamesDoc, paramDoc);
                string docTitle = DocNum.Tables["docnumber"].Rows[0][0].ToString();


                transaction.Commit();

                return docTitle;
            }
            catch (Exception ex)
            {

                transaction.Rollback();
                throw ex;
            }

    }

after running the method several times, user ended up getting the error message below.

the timeout period elapsed prior to obtaining a connection from the
pool

Error occurred because I haven't closed the connection and the connection pool has over flown.

I tried to close the connection before committing the transaction.

transaction.Connection.Close();  
transaction.Commit();

Then got the following error.

This SqlTransaction has completed; it is no longer usable

How can I close the connection to avoid the error?

Best Answer

You cannot exhaust your pool by using a single connection. You need to close all connections you are using. Preferably after the transaction has ended one way or another. using blocks are your friend for almost all database related objects.

By the way:

throw ex;

This damages your exception by replacing the original stacktrace. Use:

throw;

to rethrow the exception you caught unchanged.