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

c#使用sqlite1.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;
            }
运行正常

相关文章

SQLite架构简单,又有Json计算能力,有时会承担Json文件/RES...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器...
安卓开发,利用SQLite实现登陆注册功能