sqlite异常:链接close()和dispose()之后任然不能释放与db文件的连接

c#使用sqlite 1.0.97.0版本,

string dbFile = @"G:\test.db";
            string connenctStr = string.Format(@"Data Source={0};Pooling=true;FailIfMissing=false", dbFile);
            SQLiteConnection m_Connection = new SQLiteConnection(connenctStr);
            m_Connection.Open();
            using (var com = m_Connection.CreateCommand())
            {
                com.CommandText = @"select 1";
                com.ExecuteNonQuery();
            }
            m_Connection.Close();
            m_Connection.Dispose();

            try
            {
                File.Delete(dbFile);
            }
            catch (Exception e)
            {
                throw e;
            }

执行代码,在删除文件时提示:

An unhandled exception of type 'System.IO.IOException' occurred in TestSqlite.exe

Additional information: 文件“G:\test.db”正由另一进程使用,因此该进程无法访问此文件。

异常。

原因是sqlite在执行SQLiteConnectionHandle.Dispose()操作时候,其实并没有真正的释放连接,只有显式调用 CLR垃圾回收之后才能真正释放连接。

参考连接 stackoverflow 问答,http://stackoverflow.com/questions/8511901/system-data-sqlite-close-not-releasing-database-file,但是即使按


照answer中给出的答案加上GC.Collect();仍然报同样异常。

还需要加上GC.WaitForPendingFinalizers()这句。参考上述博客中11楼的回答。

代码修改后如下

            string dbFile = @"G:\test.db";
            string connenctStr = string.Format(@"Data Source={0};Pooling=true;FailIfMissing=false", dbFile);
            SQLiteConnection m_Connection = new SQLiteConnection(connenctStr);
            m_Connection.Open();
            using (var com = m_Connection.CreateCommand())
            {
                com.CommandText = @"select 1";
                com.ExecuteNonQuery();
            }
            m_Connection.Close();
            m_Connection.Dispose();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            try
            {
                File.Delete(dbFile);
            }
            catch (Exception e)
            {
                throw e;
            }

运行正常


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值