简体   繁体   中英

SqlConnection - The timeout period elapsed prior to obtaining a connection from the pool

Can anyone see anywhere in the code below where connections might leak out for this logging to database code? I am receiving the error in the title occasionally but not always when running this application.

The only thing I have left to try is to include: SqlConnection.ClearAllPools(); before the dispose. Would this help or cause undue load?

   private void InsertToDb(EventLogDto e, string connectionString)
    {
        var cmd = new SqlCommand();
        using (var sqlConn = new SqlConnection(connectionString))
        {
            try
            {
                // Open the connection.
                sqlConn.Open();

                // Build the SqlCommand object
                cmd = BuildSqlCommand(e, sqlConn);

                // Execute the Stored Proc.
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Logger.Instance.Fatal(ex);
            }
            finally
            {
                sqlConn.Close();
                sqlConn.Dispose();
            }
        }
    }

where BuldSqlCommand(e, sqlConn); is:

private SqlCommand BuildSqlCommand(EventLogDto e, SqlConnection sqlConn)
    {
        var cmd = new SqlCommand
        {
            CommandText = "dbo.InsertEventLog",
            CommandType = CommandType.StoredProcedure,
            Connection = sqlConn
        };

        InsertValue(cmd.Parameters, "@EventId", e.EventId);
        InsertValue(cmd.Parameters, "@DateCreated", e.EventDate);
        InsertValue(cmd.Parameters, "@Severity", e.Severity);
        InsertValue(cmd.Parameters, "@Message", e.Message);
        InsertValue(cmd.Parameters, "@Source", e.Source);
        InsertValue(cmd.Parameters, "@TargetSite", e.TargetSite);
        InsertValue(cmd.Parameters, "@StackTrace", e.StackTrace);

        return cmd;
    }

Try this and see if it helps.

try {
    using (var sqlConn = new SqlConnection(myConnectionString)) {
        using (SqlCommand cmd = sqlConn.CreateCommand()) {
            sqlConn.Open();
            AttachParameters(cmd, e);
            cmd.ExecuteNonQuery();
        }
    }
} catch (Exception ex) {
    Logger.Instance.Fatal(ex);
}

If its still happening I'd guess its because of Fatal().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM