Bubble Bub
Bubble Bub

Reputation: 701

C# - connection leaking returning from class method

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!.

Upvotes: 3

Views: 393

Answers (3)

Piotr Stapp
Piotr Stapp

Reputation: 19830

You have two options

  1. Use using statement
  2. In finally instead of Close call Dispose

Both 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
    }
 }

Upvotes: 3

Milad Hosseinpanahi
Milad Hosseinpanahi

Reputation: 1495

   catch
      {
          oConn.GetConnection.Close();
      }
   finally
      {
          oConn.GetConnection.Close();
      }

take a look at this part, finally will happen whatever happens in try catch block, so remove

catch
  {
      oConn.GetConnection.Close();
  }

from your code

Upvotes: 0

MPelletier
MPelletier

Reputation: 16687

SqlConnection is a disposable class, and you should dispose of it when you're done.

In short, have your class itself implement IDisposable (follow the example there. It's pretty textbook).

Upvotes: 0

Related Questions