内部 .Net Framework 数据提供程序错误 1

17

我正在使用Visual Studio 2012 Ultimate(带有所有服务包)、C#和.NET Framework 4.5开发WinForm应用程序。

我遇到了以下异常:

Internal .Net Framework Data Provider error 1

使用这个技术栈:

   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() 

在析构函数中:

~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;
    }
}

我在this.conn.Close();这一行遇到了异常。

conn是一个private SqlConnection conn = null;

你知道为什么会出现这种情况吗?


有一些错误,你在释放之后不需要 this.conn=null;,我建议在调用 DisposeCurrentConnection() 之前先处理你的命令。 - Reza
2个回答

23

我已经在这里找到了解决方案。

基本上可以归结为以下内容:

注意

不要在类的Finalize方法中调用Connection、DataReader或任何其他托管对象的Close或Dispose方法。 在终结器中,您应该只释放类直接拥有的非托管资源。 如果您的类不拥有任何非托管资源,请不要在类定义中包括Finalize方法。有关更多信息,请参阅垃圾回收。


1
如果您无条件地释放连接,也可以在 Dispose() 方法中间接遇到此问题。您应该只在 if (disposing) 的情况下释放它。 - Metalogic

1

这不是答案,但我强烈建议您使用using来处理连接。这样您就不需要担心对象的处理了。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接