chillitom chillitom - 5 months ago 11x
SQL Question

How to query the current size of the MySQL's .Net connector's connection pool?

Is there a programmatic way to find the current number of open connections to the database that are being maintained by the .Net connector/MySql.Data.dll?

I'm interested in collecting this information within the same program as the library is used.


Connection pooling is performed on the client side. To get access to it, you'll need to use reflection to get to the MySqlPoolManager and MySqlPool classes, which are both internal to the MySql.Data assembly.

Essentially, you'll want to use reflection to get to the pool. Here's how:

Assembly ms = Assembly.LoadFrom("MySql.Data.dll");
Type type = ms.GetType("MySql.Data.MySqlClient.MySqlPoolManager");
MethodInfo mi = type.GetMethod("GetPool", BindingFlags.Static | BindingFlags.Public);
var pool = mi.Invoke(null, new object[] { new MySqlConnectionStringBuilder(connString) });

You'll notice that you have to pass in a MySqlConnectionStringBuilder object. It creates a separate pool for each connection string, so use the same connection string you use in your app (it needs to be completely identical).

You can then access the private pool fields and properties (again, using reflection), to get the information you need. In particular, the "available" field and the "NumConnections" properties are probably what will be of interest to you. There's also the "idlePool" (a Queue<>) and the "inUsePool" (a List<>) which you can access as well, particularly the counts.