任何人都可以在下面代码中的任何地方看到此日志记录到数据库代码的连接可能会泄漏吗?我偶尔会收到标题中的错误,但在运行此应用程序时并非总是如此。
我唯一要尝试的是包括: SqlConnection.ClearAllPools(); 处置前。这会帮助还是导致过度负荷?
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();
}
}
}
其中 BuldSqlCommand(e, sqlConn); 是:
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;
}