共用方式為


EntLib 3.1 DAAB: Be careful with the ExecuteReader

The EntLib 3.1 is simply superb, right?! Well, I would give a typical consultant answer... "It depends!". It depends on the developers who are using it and it depends on motivation of the developers to know the component before "copy-pasting" code and method calls.

Case in point is the exceptionally well written Data Access Application Block (a.k.a. DAAB). My team is involved in developing an e-commerce web site for a large automotive retailer and is using this DAAB beauty to ease the development efforts. We integrated the default provided DAAB DLLs into the solution and happily developed the data layers for our system. It was working just fine on each of the dev machines;  I put the solution to a production server so that our clients can appreciate the beauty of it! The next thing I know, the site starts timing out for some of the calls. I went into the logs and found that the connection timeout errors were rampant! I started digging in to the code and found that we had used one particular method a lot and this was the only method that did not close the connection "automatically" - the ExecuteReader method.

If you think about it logically, it makes a lot of sense NOT to close the connection automatically as the DAAB does not have any idea as to when the reader will move out of scope. So the correct code snippet to use is

    1:  Database db = DatabaseFactory.CreateDatabase();
    2:   
    3:  DbCommand dbCommand = db.GetSqlStringCommand("Select Name, Address From Customers");
    4:  using (IDataReader dataReader = db.ExecuteReader(dbCommand))
    5:  {
    6:      // Process results
    7:  } 
  

The full reasoning is well explained at the MSDN Site here

Comments

  • Anonymous
    July 10, 2008
    The comment has been removed