I has returning a connection from a class method in Connection class. In my another class, I instantiate the connection class to open the connection. I has close the connection as well but it seem like has connection leak. Any idea how I can fix it. My code as below
public class Connection
{
private SqlConnection _oConn;
public SqlConnection GetConnection
{
get
{
if (_oConn == null)
{
string sConnString = ConfigurationManager.ConnectionStrings["bplocator_database_connection"].ConnectionString;
_oConn = new SqlConnection(sConnString);
}
return _oConn;
}
}
}
In another class file, i call this connection class
private BPAdmin.data.Connection oConn
{
get
{
if (_oConn == null)
{
_oConn = new BPAdmin.data.Connection();
}
return _oConn;
}
}
public void getData
{
try
{
oConn.GetConnection.Open();
//Do something
}
catch
{
oConn.GetConnection.Close();
}
finally
{
oConn.GetConnection.Close();
}
}
I found that this cause a connection leaking and it cause application pool reached max. Any idea whats wrong and how I can fix it. Please help!.
You have two options
using statementfinally instead of Close call DisposeBoth solutions should fix the problem.
UPDATE: how to use using statement
Because oConn always return a new object in getData you can use following:
public void getData()
{
try
{
using(var conection=oConn.GetConnection)
{
//execute your query
}
}
catch
{
//do something to show user an error or just log it
}
finally
{
//you do not have to close connection because using statement will do this for you
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With