Tuesday, 15 May 2012

vb.net - Error with the Using Statement and Lazy Initialized Property -


A invalid operation expiration will be thrown in the code below: ConnectionString property has not been started. Calling on line in the method of loading exceptions. Open (). If I use try-end statement instead of using the statement, then everything works correctly as well as anyone can interpret SqlClient.SqlConnection, with the exception statement being used? Private connection SomeEntity Private _Connection SqlClient.SqlConnection Private _ConnectionString String as protected ReadOnly property connection () If the _Connection is nothing, then _Connection = New SqlClient.SqlConnection (_ConnectionString) End then return _Connection from the end to the other end property using the Connection.Open connection () as the public sub-new go (as byVal connectionstring string) _ConnectionString = connectionstring end subsystem subload (ByVal key as integer). End End End End Class

You have failed to mention an important piece of information: This is the first time the load () succeeds, but then remains unsuccessful for ever. Using the

, the settlement () is called the O.N using the block using the variable used. In your scenario:

  1. The load () is called
  2. Using the received connection call property property
  3. _Connection a new one SqlConnection is set to
  4. < P>

    The SqlConnection object still exists, and is still indicated by _Connection, it is no longer in a useful state, because it is displacement () D. When the second call (to load) comes in:

    1. The load () is called
    2. Using the statement the call receives the connection property < / Li>
    3. _Connection is still pointing to a (useless) SqlConnection object, so it is not nothing, and a new SqlConnection object returns
    4. (useless) connection
    5. Do not get ready to open () is called on the connection - in an unavoidable condition And invalid operation triggers exceptions

    You are mixing anti-views for connection management, keeping the connection object around as a member of the class indicates that you have someEntity Want to keep alive connections for the life of the object, but using the use indicates that you can create and destroy the connection with each use to fly Are there.


No comments:

Post a Comment