我刚刚开始将 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/