Ado.Net - How to use connection pooling?

左心房为你撑大大i 提交于 2020-01-03 18:25:22

问题


.Net allows connection pooling which based on what I've read is simply by adding parameters to App.config

The question is, am I suppose to do anything in my code to use the connection pool? In my code I open a connection every time data is needed and I close it as soon as I'm done. Am i suppose to do anything special to reuse connections?


回答1:


You don't need to do anything special as long as your connections use the same connection string. Use the connection, close it and will automatically return to the pool.

From SQL Server connection pooling:

Connections are pooled per process, per application domain, per connection string and when integrated security is used, per Windows identity. Connection strings must also be an exact match; keywords supplied in a different order for the same connection will be pooled separately.

You can configure certain pool related options in the connection string itself:

  • Pooling (enabled by default)
  • Connection Lifetime (or Load Balance Timeout)
  • Enlist
  • Max Pool Size
  • Min Pool Size



回答2:


The point is to not do anything to re-use connections :) If you store the connection and re-use it, the pool is defeated.

A good pattern is to take advantage of IDisposable and using. For the ado.net connection classes, dispose calls close. If you do that, you can't go wrong.

using (conn = new SqlConnection(...))
{
    // use the connection
}



回答3:


You do not have to do anything its enabled by default. If you wish to disable it you can set the pooling value to false in the connection string. Below is a nice video which explains the same in more detail with demonstration.

http://www.youtube.com/watch?v=nwBBd9GrcqI



来源:https://stackoverflow.com/questions/7543176/ado-net-how-to-use-connection-pooling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!