从C#2.1驱动程序正确关闭MongoDB数据库连接? [英] Properly shutting down MongoDB database connection from C# 2.1 driver?

查看:289
本文介绍了从C#2.1驱动程序正确关闭MongoDB数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am just getting started with integrating MongoDB into my application and I have ran into a few questions. In my application I am using the newest 2.1 version of the MongoDB C# driver and only using MongoDB for application logging.

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

Currently before showing my main application Form I first check to see if mongod.exe is running and if not I start it. Then when my main Form is shown it opens a connection to the database for use seen below.

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

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

My question is how I should properly shutdown this connection when my application is closing?

在使mongod.exe处于运行状态还是每次应用程序关闭时都退出它时,还有一些我应该考虑的因素吗?

Also are there in considerations I should take into account in leaving mongod.exe running versus exiting it each time the application closes?

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

I have searched a few times trying to figure out if there is a proper way to shutdown the connection but have found nothing very specific. There is an old SO post (that I can't seem to find now) mentioning a .Dispose method, though I cannot seem to find it in the newest driver nor from my IDE's auto complete.

推荐答案

从当前版本的MongoDB(对于MongoDB.Driverv2.0.1.27)开始,无需关闭或处置连接.客户端会自动处理它.

As of today's version of MongoDB (v2.0.1.27 for MongoDB.Driver), there's no need to close or dispose of connections. The client handles it automatically.

来自文档:

MongoClient对象将成为根对象.它是线程安全的,是处理连接到服务器,监视服务器以及对这些服务器执行操作所需的全部. [...] 建议将MongoClient实例存储为全局变量,既可以作为静态变量,也可以存储在具有单例生命周期的IoC容器中.但是,使用相同设置创建的多个MongoClient实例将使用下面的相同连接池.

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.

在此SO答案中有部分/旧的线程安全MongoDB类列表 .

There's a partial/old list of thread-safe MongoDB classes in this SO answer.

这篇关于从C#2.1驱动程序正确关闭MongoDB数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆