简体   繁体   English

C#/ MongoDB:如何保持连接存活?

[英]C# / MongoDB : How do I keep a connection alive?

I'm writing a C# application which accesses a remote MongoDB. 我正在编写一个访问远程MongoDB的C#应用​​程序。 How do I go about persisting the connection while I query the database? 在查询数据库时如何继续连接? Should I implement some sort of open/close mechanism? 我应该实施某种开/关机制吗? Or would it be better to connect once and have a time-out? 或者连接一次并暂停时会更好吗? I'm usign the official MongoDB / C# driver. 我正在使用MongoDB / C#官方驱动程序。

Under the hood the MongoDB C# driver maintains a connection pool, which is fairly typical in .NET. 在引擎盖下,MongoDB C#驱动程序维护一个连接池,这在.NET中非常典型。 The pool works by maintaining a number of open connections for you. 该池通过为您维护一些打开的连接来工作。 When you need a connection the pool will give you an existing connection (provided one is available). 当您需要连接时,池将为您提供现有连接(如果有连接)。

The issue to avoid is a leak in your connections--if connections are opened and not closed again then you will undermine the gains of the connection pool and will need to open an additional connection every time. 要避免的问题是连接中的泄漏 - 如果连接被打开而没有再次关闭,那么您将破坏连接池的收益,并且每次都需要打开一个额外的连接。 Also, if there is a connection leak, there's the chance it will consume extra resources on your client as well as the server. 此外,如果存在连接泄漏,则可能会在客户端和服务器上消耗额外的资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM