c# - 从 C# 2.1 驱动程序正确关闭 MongoDB 数据库连接?

标签 c# mongodb

我刚刚开始将 MongoDB 集成到我的应用程序中,并且遇到了一些问题。在我的应用程序中,我使用的是最新的 2.1 版本的 MongoDB C# 驱动程序,并且仅使用 MongoDB 进行应用程序日志记录。

目前在显示我的主应用程序 Form 之前,我首先检查 mongod.exe 是否正在运行,如果没有则启动它。然后,当我的主 Form 显示出来时,它会打开与数据库的连接以供使用,如下所示。

public void Open()
{
    Client = new MongoClient("mongodb://localhost:27017");
    Database = Client.GetDatabase(DBName);
    Collection = Database.GetCollection<BsonDocument>(ColName);
}

我的问题是当我的应用程序关闭时我应该如何正确关闭此连接?

在每次应用程序关闭时让 mongod.exe 运行还是退出时,我还应该考虑哪些因素?

我已经搜索了几次,试图找出是否有适当的方法来关闭连接,但没有找到任何非常具体的方法。有一个旧的 SO 帖子(我现在似乎找不到)提到了一个 .Dispose 方法,尽管我似乎无法在最新的驱动程序中找到它,也无法从我的 IDE 的自动完成中找到它。

最佳答案

从今天的 MongoDB 版本(v2.0.1.27 for MongoDB.Driver)开始,无需关闭或释放连接。客户端自动处理。

来自 the docs :

A MongoClient object will be the root object. It is thread-safe and is all that is needed to handle connecting to servers, monitoring servers, and performing operations against those servers. [...] It is recommended to store a MongoClient instance in a global place, either as a static variable or in an IoC container with a singleton lifetime. However, multiple MongoClient instances created with the same settings will utilize the same connection pools underneath.

有一个部分/旧的线程安全 MongoDB 类列表 in this SO answer .

关于c# - 从 C# 2.1 驱动程序正确关闭 MongoDB 数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703051/

相关文章:

c# - 无法使用 PRISM 5、MVVM 和 EF 6 在 WPF 中刷新 DataGrid

c# - Fluent NHibernate SqlDateTime 溢出异常

c# - UWP - 项目中包含的文件出现 UnauthorizedAccessException

database - 如何使用 bool 属性检查运行查询

c# - 将 JSON 写入流而不在内存中缓冲字符串

c# - 如何在程序的 app.config 文件中存储文件路径?

mongodb - Go Mongo 仅更新非零值

c# - 使用 C# 将多个文档插入 Mongodb 的最快方法

c# - 使用 C# 驱动程序分页 MongoDB 查询

python - Django MongoDB 迁移警告