gpt4 book ai didi

C# 如何 "verify"新连接实际上正在从连接池中重用

转载 作者:搜寻专家 更新时间:2023-10-30 20:11:43 24 4
gpt4 key购买 nike

我有一个简单的 C# 代码,我在其中尝试多次打开和关闭连接。我如何才能确保我的新连接来自连接池并且它不会访问数据库?

using System;
using System.Data;
using System.Data.Odbc;
using System.Collections.Generic;

namespace LBSService
{
class MyClass {
public static OdbcConnection connection = null;
public void TestConnection()
{
string connectionstring = @"Dsn=my_database.IServer;Host=IServer;
Database=my_database;Uid=informix;
Pwd=Some@123";

for (int i = 1; i <= 50; i++)
{
string StrQuery = "select * from capture_files";
connection = new OdbcConnection(connectionstring);
connection.Open();
connection.Close();
}
}
}
}

我有必须打开 ODBC 连接的限制,因此首选与 ODBC 相关的答案。

我的“连接”对象中是否有任何数据成员或我可以实际看到池中有多少未使用的连接以及我的应用程序使用了多少的东西。

提前致谢...

最佳答案

"How can I ensure that my new connections are coming from connection pool and that it is not hitting the database"

这是一个有点错误的逻辑。连接池在客户端。即使您重用池中的连接,任何命令仍然必须访问数据库。

如果您有完全相同的连接字符串(甚至大小写),那么您将重用池中的连接(假设它已打开,即默认值)。

连接池存在的原因是因为建立连接需要一些开销。

SQL Server Connection Pooling :

Connecting to a database server typically consists of several time-consuming steps. A physical channel such as a socket or a named pipe must be established, the initial handshake with the server must occur, the connection string information must be parsed, the connection must be authenticated by the server, checks must be run for enlisting in the current transaction, and so on.

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

Only connections with the same configuration can be pooled. ADO.NET keeps several pools at the same time, one for each configuration. Connections are separated into pools by connection string, and by Windows identity when integrated security is used. Connections are also pooled based on whether they are enlisted in a transaction.

关于C# 如何 "verify"新连接实际上正在从连接池中重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9002939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com