none
Why am I getting an error durring cleanup? RRS feed

  • Question

  • Trying to disconnect from the database properly when the application form is closed and I keep getting this error: System.InvalidOperationException

     

    Code Snippet

    Private database As SqlClient.SqlConnection

     

    Protected Overrides Sub Finalize()

    Debug.WriteLine("DAT - Finalizing Data Manager")

    If database.State = ConnectionState.Open Then

    Debug.WriteLine("CONNECTION OPEN")

    database.Close()

    End If

    MyBase.Finalize()

    End Sub

     

     

    Tuesday, December 2, 2008 5:05 PM

Answers

  • I do not think you can call Close method of database connection in Finalize. You should do it before Finalize called. Actually you should not keep connection opened all the time and close it each time when your action against database completes. Then reopen connection before you need to execute another SQL statement. With the connection pooling, you should not see any big difference in performance if you switch to this model, but it will minimize resources usage and will prevent such errors.

    Wednesday, December 3, 2008 11:41 AM
    Moderator

All replies

  • Can you provide more detailed error stack info? 

    Wednesday, December 3, 2008 7:44 AM
    Answerer
  • I do not think you can call Close method of database connection in Finalize. You should do it before Finalize called. Actually you should not keep connection opened all the time and close it each time when your action against database completes. Then reopen connection before you need to execute another SQL statement. With the connection pooling, you should not see any big difference in performance if you switch to this model, but it will minimize resources usage and will prevent such errors.

    Wednesday, December 3, 2008 11:41 AM
    Moderator
  • I join VMazur - we do not recommend closing the database in finalizer call.

     

    Make sure the database connection is closed before the code reaches the finalizer, so 'using' statement is your friend.

     

    using(SqlConnection connection = new SqlConnection(...))

    {

      connection.Open();

     

      // do the work here

     

    } // connection is disposed and returned to the pool if pooling is enabled (and it is enabled by default)

     

    Note that in this case the connection will be closed even in case of exception inside the 'using' block.

     

    But, if you do not want to mess with closing and reopening the connection every time, or if from some reason you have to keep it open, in your case the (not the best) alternative would be closing the connection in Form.FormClosed event.

     

    Regards,

     Nissim

    Friday, December 5, 2008 11:20 PM
    Moderator