We are getting a severe memory leak in our C# application. We insulated all the possible suspects and found that the data layer - SqlConnection - causing the memory leak. We are executing many SqlConnection requests. Approximately 10 requests per second. And we are getting a leak of 200M per day.
We are using the following SqlConnection access as base class:
public class Access : IDisposable
{
protected SqlConnection connection;
private readonly object locker = new object();
protected void OpenConnection()
{
if (this.connection == null)
{
lock (locker)
{
if (this.connection == null)
{
string conn = Config.Data["data"]["mainConnString"];
this.connection = new SqlConnection(conn);
this.connection.Open();
}
}
}
else if (this.connection.State == System.Data.ConnectionState.Closed)
{
lock (locker)
{
if (this.connection.State == System.Data.ConnectionState.Closed)
{
this.connection.Open();
}
}
}
}
public void Dispose()
{
if (this.connection != null)
{
this.connection.Close();
this.connection.Dispose();
}
}
}
All our SqlConnection classes inherit from this base class above, and we surround each SqlConnection usage with a using block
So for instance if we have a Product table and a ProductAccess the inherits the Access class.
We are using the following code:
using (var acceess = new ProductAccess ())
{
Product product = acceess .GetProductById (id);
}
Therefore each time we use SqlConnection we create a new one and after we finish using it we dispose it (because the usage is surrounded by using block)
We are using c# v4.0.30319 and Microsoft SQL Server 2008 R2.
Anyone knows or have any ideas why this memory leak occurred?
Maybe it is related to garbage collection issue or garbage collection configuration?
Maybe this leak related to GC.SuppressFinalize(this) method call that the SqlConnection dispose() method call?
Thanks