I have inherited a web framework whereby the previous developer has opened and closed his database connections in the init/unload methods of the page life cycle. Essentially constructor is like this (simplified to demonstrate the 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();
}
}
}
Development has been pretty fast since i got here so I never stopped to consider it. Recently, visits have been up and we've started getting the dreaded "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool..." error.
I'm currently going through the rest of the code looking for possible connection leaks, but the above code has never quite sat right with me and I want to eliminate it as a potential culprit. On to the question then;
Can i rely on the "unload" method ALWAYS being called, even in the event of an exception? Or can anyone see any other potential issues using the above pattern that would make it a prime suspect for these connection leaks?
Cheers,
Mikey
EDIT: In debugging, the unload method always gets called even if there is an exception. I really just need to know of any scenarios where this method would not be called so i can figure out if this is the bit i need to be refactoring first.
EDIT: Thanks to those who have responded so far but please no more recommendations about the IDisposable class, or the "using" or "catch/finally" patterns - This wasn't what my question was! My question is specifically whether a page could ever run its "Init" event but then fail to run is "Unload" event, and why this might happen.