Closing a connection by unloading

I inherited a web structure in which a previous developer opened and closed his database connections in the init / unload methods of the page life cycle. Essentially a constructor is similar to this (simplified to show a point);

public class BasePage
{
   protected DBConnection _conn;

   public BasePage()
   {
      Init += StartConnection;
      Unload += EndConnection;
   }

   private void StartConnection(object sender, EventArgs e)
   {
      _conn = new DBConnection(Application["connectionstring"].ToString());   
   }

   private void EndConnection(object sender, EventArgs e)
   {
      if (_conn == null)
         return;

      if (_conn.Connection.State == ConnectionState.Open)
      {
     _conn.Close();
         _conn.Dispose();
      }
   }
}

The development was quite quick, since I got here, so I never stopped considering it. Recently, visits have been completed, and we began to receive the dreaded "Timed out". The timeout period elapsed before receiving the connection from the pool ... "

I am currently browsing the rest of the code, which is looking for possible communication leaks, but the code above has never sat right with me, and I want to eliminate it as a potential culprit. Then to the question:

"", , ? - , , ?

,

EDIT: , . , , , , .

EDIT: , , IDisposable "" "/". ! , - "Init", "Unload", .

+5
5

, , System.Web.UI.Page, ProcessRequestCleanup(), . finally, try, ProcessRequest. PreInit Render. , Unload ( async cross page), .

, .

+2

soemthing ,

using( SqlConnection)
{

}

,

public class SqlConnectionManager
{
    public SqlConnection GetSqlConnectionManager()
    {
       //create and return connection
       //SqlConnection con = new SqlConnection();
       //return con;
     }

}

SqlConnection conn = null;
using (conn = (new SqlConnectionManager()).GetSqlConnectionManager())
{
     //do work with connection
}

, , , .

+2

: .net 4, , .

.net 2.0, .

+1

A () (- VS2010,.net v4) , Unload , ( , Page_Load), , .

, , dispose ', .

_conn , , BasePage, _conn . :

  • _conn.Close() . , EndConnection.

  • _conn, null DBConnection.

EndConnection, _conn .

private void EndConnection(object sender, EventArgs e)
{
    if (_conn == null)
    {
       return;
    }
    if (_conn.Connection.State == ConnectionState.Open)
    {
         _conn.Close();
    }
    _conn.Dispose(); // always dispose even if not actually open. It may have been closed explicitly elsewhere.
}

2 EndConnection. _conn private getter:

private DBConnection _conn;

protected DBConnection Connection {
     get 
     {
         return _conn;
     }
}

- _conn.

, DBConnection ? , "_conn.Connection.State", _conn.State. , , Dispose DBConnection Connection.

+1

. .

, ? Unload , .

This Unload question on StackOverflow has a similar problem that you are facing.

0
source

All Articles