Closing a conneciton in the “unload” method

前端 未结 5 1054
故里飘歌
故里飘歌 2021-01-18 15:31

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

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 15:57

    A (very) quick test (VS2010 web server, .net v4) has shown me that the Unload event is called when an unhandled exception is raised (at least if raised in Page_Load), so the principle looks like it should work.

    The pattern as listed in the example is only dispose'ing the connection if the connection was open.

    As _conn is protected, pages descended from BasePage can interact with _conn and modify its value. There are two ways for descendant classes to break the pattern:

    1. Call _conn.Close() directly. If the connection is not open, it is not disposed in EndConnection.

    2. Modify the value of _conn by either setting it to null or assigning a new instance of DBConnection to it.

    Consider changing your EndConnection method, so that _conn is always disposed.

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

    Case 2 can't be caught by EndConnection. Consider making _conn private and providing a getter property:

    private DBConnection _conn;
    
    protected DBConnection Connection {
         get 
         {
             return _conn;
         }
    }
    

    which prevents descendant classes from changing the value of _conn.

    Lastly, is DBConnection a class of your own? I only ask as you quote "_conn.Connection.State" rather than just _conn.State. If so, just double check that the Dispose method of DBConnection disposes its Connection instance correctly.

提交回复
热议问题