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

时间:2022-08-21 20:55:29

I'm writing a C# application which accesses a remote MongoDB. 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#应用​​程序。在查询数据库时如何继续连接?我应该实施某种开/关机制吗?或者连接一次并超时会更好吗?我正在使用MongoDB / C#官方驱动程序。

1 个解决方案

#1


4  

Under the hood the MongoDB C# driver maintains a connection pool, which is fairly typical in .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).

在引擎盖下,MongoDB C#驱动程序维护一个连接池,这在.NET中非常典型。该池通过为您维护一些打开的连接来工作。当您需要连接时,池将为您提供现有连接(如果有连接)。

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.

要避免的问题是连接泄漏 - 如果连接打开而不是再次关闭,那么您将破坏连接池的收益,并且每次都需要打开一个额外的连接。此外,如果存在连接泄漏,则可能会在客户端和服务器上消耗额外的资源。

#1


4  

Under the hood the MongoDB C# driver maintains a connection pool, which is fairly typical in .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).

在引擎盖下,MongoDB C#驱动程序维护一个连接池,这在.NET中非常典型。该池通过为您维护一些打开的连接来工作。当您需要连接时,池将为您提供现有连接(如果有连接)。

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.

要避免的问题是连接泄漏 - 如果连接打开而不是再次关闭,那么您将破坏连接池的收益,并且每次都需要打开一个额外的连接。此外,如果存在连接泄漏,则可能会在客户端和服务器上消耗额外的资源。