simply put, my sqlservr.exe is memory leaking when ever my service uses it. So the question is, Where and why! 🙁
I intialise my connection as nulls. and have a finally clause to ensure they are closed… (ive also tried .dispose on the datareader, but doesnt help).
I’ve tried identifying the problem for over a day. All I can tell is that it is here somewhere.
private Int32 GetCount(String From, String Where)
{
//Build SQL string from given parameters.
String sql = "SET dateformat DMY SELECT COUNT(*) as Count FROM " + From + " WHERE " + Where;
SqlDataReader dataCount = null;
SqlCommand sqlCommCount = null;
SqlConnection sqlConCount = null;
try
{
sqlCommCount = new SqlCommand();
sqlConCount = new SqlConnection();
sqlCommCount.Connection = sqlConCount;
sqlConCount.ConnectionString = "connectionstring";
sqlCommCount.CommandText = sql;
sqlConCount.Open();
dataCount = sqlCommCount.ExecuteReader();
while (dataCount.Read())
{
return Convert.ToInt32(dataCount["Count"]);
}
return 0;
}
finally
{
sqlConCount.Close();
sqlCommCount.Dispose();
if (dataCount != null)
dataCount.Close();
}
}
SOLVED:
-
There is no leak.
-
I hate Sqlserver for not telling me it caches memory that isnt in use when connections are madee, so just increases and increases (until it is needed).
Refactor your code with this keyword: using
Memory occupation is not deterministic, in you sample the effective memory used by the executable will be freed only when Garbage Collection occurs, so you can see memory increase but this could be not an issue, it will be collected sooner or later and memory will return to a proper value.
After seeing the comment, then the problem seems not to be in your C# code (also if using the using keyword it’s a good idea!), if there is a problem…
SQL Server will increase memory occupation until it has memory available, it’s designed to work that way. In your sample each time you pass a new where clause it will cache the SQL statement and so memory usage will increase until you have memory available.
In this case I suggest you to refactor your code to use at least SQL parameters to create the where clause, so the SQL will always remains the same and only the parameters change, this way SQL server will cache only one SQL statement and not thousands. Better yet is to create a stored procedure, but parameters are usually enough.
Keep also in mind that the way you’re building your SQL statement is really unsafe and could lead to SQL injection attacks, using parameters will fix that too.
Regards
Massimo