Internal .Net Framework Data Provider error 1

2019-02-21 14:56发布

问题:

I'm developing a WinForm app with Visual Studio 2012 Ultimate edition with all service pack, C# and .NET Framework 4.5.

I get this exception:

Internal .Net Framework Data Provider error 1

With this stack:

   en System.Data.ProviderBase.DbConnectionInternal.PrePush(Object expectedOwner)
   en System.Data.ProviderBase.DbConnectionPool.PutObject(DbConnectionInternal obj, Object owningObject)
   en System.Data.ProviderBase.DbConnectionInternal.CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
   en System.Data.SqlClient.SqlConnection.CloseInnerConnection()
   en System.Data.SqlClient.SqlConnection.Close()
   en AdoData.TRZIC.DisposeCurrentConnection() 
   en AdoData.TRZIC.Finalize() 

In the destructor:

~TRZIC()
{
    DisposeCurrentConnection();

    if (this.getCodeCmd != null)
        this.getCodeCmd.Dispose();
}

private void DisposeCurrentConnection()
{
    if (this.conn != null)
    {
        if (this.conn.State == ConnectionState.Open)
            this.conn.Close();

        this.conn.Dispose();
        this.conn = null;
    }
}

I get the exception in line this.conn.Close();.

And conn is private SqlConnection conn = null;

Do you know why?

回答1:

I have found the solution here.

Basically it boils down to this:

Caution

Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition. For more information, see Garbage Collection.



回答2:

This is not answer but I strongly suggest you to dispose connections using using. Then you don't need to concern about disposing objects.

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
    try    
    {
        connection.Open();
        SqlCommand command = new SqlCommand("......", connection);
        command.ExecuteNonQuery();    
    } 
    catch (Exception) 
    { 
        /*Handle error*/ 
    }
}