如何关闭使用 System.Data.SQLite 和 DbContext 打开的 sqlite 文件?

问题描述 投票:0回答:1

在用于使用 System.Data.SQLite 创建和访问 SQLite 数据库的此演练我的 EF6 重新创建中,我发现对数据库的任何访问都会使数据库文件的文件句柄在我处理完之后很长时间保持打开状态我创建的唯一一次性对象:DbContext。

这可以防止我在完成数据库文件后删除它(例如,在单元测试结束时,或者当我的应用程序的用户请求它时)。

你可以看到我使用

DbContext
是多么简单,以及关闭后
File.Delete
如何失败:

using (var context = new ChinookContext())
{
    var artists = from a in context.Artists
                    where a.Name.StartsWith("A")
                    orderby a.Name
                    select a;

    foreach (var artist in artists)
    {
        Console.WriteLine(artist.Name);
    }
}

// I've disposed of the DbContext. All handles to the sqlite database file SHOULD
// have been released by now.
// Yet, this next line fails because the file is still locked.
File.Delete("Chinook_Sqlite_AutoIncrementPKs.sqlite");

github 上的完整项目上下文

对于关闭文件句柄我缺少什么有什么想法吗?

顺便说一句,我知道关于文件锁的常见问题解答#22仅在我处理命令、数据读取器等时才会被释放,但我自己还没有打开任何这些,所以我不知道如何才能处理掉它们。

c# database entity-framework sqlite ado.net
1个回答
0
投票

无需GC收集。如果要确定性地关闭文件句柄,则需要使用“Pooling=false”创建 SQLite 连接字符串。如果启用池化,则即使 GC 也可能不会关闭文件,因为池可能会缓存连接。

© www.soinside.com 2019 - 2024. All rights reserved.