sqlite錯誤:close和dispose后不能釋放與db文件的連接
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;
}
執(zhí)行代碼,在刪除文件時提示:
An unhandled exception of type 'System.IO.IOException' occurred in TestSqlite.exe
Additional information: 文件“G:\test.db”正由另一進程使用,因此該進程無法訪問此文件。
異常。
原因是sqlite在執(zhí)行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;
}
運行正常
dispose與close()的區(qū)別
Dispose了,就必須再Create一次
而Close()后,還可以再Open(),
而Dispose后,對象都不存在了,就不能Open()了
Dispose是對于對象自身而言的,Close是對于連接數(shù)據(jù)庫而言的
如對本文有疑問,請?zhí)峤坏浇涣髡搲瑥V大熱心網(wǎng)友會為你解答??! 點擊進入論壇