Properly(正确地) shutting down MongoDB database connection from C# 2.1 driver?

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.

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?

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

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.

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.

From 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.

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

  • This is how I am handling my IMongoClient, it is in a singleton logging class that all of my application can access. I guess this answer also basically convinces me that it needs nothing special to close it. // Though I am still partially unsure if I should keep the Mongo daemon running after the application is closed. – KDecker

The question seems to have been already kinda asked here at When should i be opening and closing MongoDB connections?

If it's accepted answer,

I would leave the connection open as re-creating the connection is costly. Mongo is fine with lots of connections, open for a long time. What you ideally should do is to share the connection with all parts of your application as a persistent connection. The C# driver should be clever enough to do this itself, so that it does not create too many connections, as internally it uses "connection pooling" that makes it even re-use connections. The docs say: "The connections to the server are handled automatically behind the scenes (a connection pool is used to increase efficiency)."

works fine for you then all well and good. Even the MongoDB C# driver's quick tour page lends the same advice -

Typically you only create one MongoClient instance for a given cluster and use it across your application. Creating multiple MongoClients will, however, still share the same pool of connections if and only if the connection strings are identical.


Otherwise, I think you can simply put your call to create the connection in a using(){} code block. It automatically calls the dispose method for you (as it implements the IDisposable pattern). You should use this block for any resource you want disposed.

  • I had seen that answer but it was more geared toward having multiple IMongoClients versus how to shut them down properly. I think ashes999 answered it mostly below. // Though I am still partially unsure if I should keep the Mongo daemon running after the application is closed. – KDecker Sep 22 '15 at 12:02

  • @KDecker: I can't see any difference between the other answer and mine. Anyway, even if you close the connection there will be no effect from MongoDB's perspective as the connection is pooled. You can close it for your peace of mind. – displayName Sep 22 '15 at 13:13

From my experience, the correct way is as answered, but even following these recommendations, I still was having random EndOfStreamException. It seems that some problems are caused by the internet provider closing the connection after some time.

I Solved it by adding:

MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };settings.MaxConnectionIdleTime = TimeSpan.FromSeconds(30);

Properly shutting down MongoDB database connection from C# 2.1 driver?相关推荐

  1. CDH5之Unexpected error.Unable to verify database connection

    在部署好CDH5(HDFS+MapReduce+Zookeeper)后,某一天想要通过web界面来添加Hive或者Oozie服务.  添加Hive组件服务: 1.报错:Unexpected error ...

  2. oracle 9i 只读模式,我的oracle 9i学习日志(6)--Starting Up and shutting down a Database

    Starting Up a Database 1.NOMOUNT 这个状态下oracle server完成下列任务: a.读取初始化参数文件: b.为SGA分配内存: c.启动后台进程: d.打开al ...

  3. Springboot Could not resolve placeholder ‘spring.data.mongodb.database’ in value “${spring.data.mong

    Springboot Could not resolve placeholder 'spring.data.mongodb.database' in value "${spring.data ...

  4. WORDPRESS 网站打不开 error establishing a database connection 、is marked as crashed and should be repa

    今天打开 gudianxiaoshuo.com 网时,显示  error establishing a database connection 网站又打不开了 这让人很生气,这个是阿里云服务器,经常出 ...

  5. WordPress网站出现Error establishing a database connection原因及解决方法

    WordPress网站出现Error establishing a database connection(建立数据库连接时出错),重启服务器或者用service mysqld restart命令(M ...

  6. 解决网站出现“Error establishing a database connection“的方法

    最近刚刚写好的一篇文章,准备同步到我的网站上去,但是打开之后却出现了"Error establishing a database connection"的字样. 如下图 可能出现的 ...

  7. iOSsqlite3的线程安全BUG IN CLIENT OF sqlite3.dylib:illegal multi-threaded access to database connection

    FMDatabase是线程不安全的,当有多线程并非访问的时候会出现崩溃,可以换用 FMDatabaseQueue来解决 FMDatabaseQueue是线程安全的 为什么要使用FMDatabaseQu ...

  8. JDBC:Java DataBase Connection

    目录 第一节:JDBC入门 1.  概念 2. JDBC驱动 3.  JDBC 访问数据库的步骤 4. 几个重要的接口和类 5.  具体操作 第二节:Dao封装 1.简单打开关闭的封装 2. 查询封装 ...

  9. CDH安装hue报Unexpected error. Unable to verify database connection

    文章目录 问题描述 解决方案 问题描述 CDH安装hue时,测试数据库连接报错 Unexpected error. Unable to verify database connection 解决方案 ...

最新文章

  1. EPANET头文件解读系列7——MEMPOOL.H
  2. php周计划表_PHP学习计划书
  3. Linux 下解压文件命令大全
  4. spring cloud各组件详解
  5. 64位有符号与无符号类型的整数
  6. python中uniform(a、b)_关于uniform的详细介绍
  7. spark集群详细搭建过程及遇到的问题解决(四)
  8. .Net Core Configuration源码探究
  9. gradle打包java项目_gradle打包java项目
  10. m 文件 dll matlab 中调用_利用USO服务将特权文件写入武器化
  11. 基本定时器TIM6和TIM7使用
  12. 云计算学习笔记---异常处理---hadoop问题处理ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: java.lang.NullPoin
  13. 如何将代码写的更加优雅?
  14. Linux系统更改时区
  15. 第六章 Python数据可视化
  16. 有韵味的女人,是成熟的女人。
  17. Log4j2高危漏洞CNVD-2021-95914分析复现修复
  18. 小米路由器的服务器无响应怎么回事,小米路由器常见问题与解决方法(高级功能)...
  19. Meta Cambria手柄曝光,主动追踪+多触觉回馈方案
  20. java基础:日志框架

热门文章

  1. 大数据分析十八般工具
  2. 计算机专业英语背什么,怎么样才能更有效快速的背诵计算机专业英语单词?
  3. Object-C Target-Action模式 回调
  4. CSS实现div滑入效果
  5. 测测你是什么人格,C++代码程序,心理学,十分准确
  6. 马慧民:大数据和产业创新
  7. 北京昌平区高新技术企业培育支持标准,补贴10万
  8. 全国计算机一级学科点数量,最新数据:39所985高校一级学科博士点数量!
  9. 学生管理系统中遇到的问题
  10. 避免摄像机穿透地形模型