问题
When using web services (we're specifically using asmx and WCF) with ASP.NET, what is the best way to establish a SQL connection? Right now, I'm establishing a new connection for each web service call, but I'm not convinced this will be too efficient when there will be thousands of users connecting. Any insight on this topic would be much appreciated.
回答1:
What you are doing is fairly standard.
Assuming you are using the same connection string, the connections will be coming from the connection pool, which is the most efficient way to get connections already.
Only doing the work required and closing the connection on each call is good practice.
One thing you can do is cache results and return the cached results for calls that are not likely to result in changed data over the life of the cache item. This will reduce database calls.
回答2:
It is strongly recommended that you always close the connection when you are finished using it so that the connection will be returned to the pool. You can do this using either the Close or Dispose methods of the Connection object, or by opening all connections inside a using statement in C#. Connections that are not explicitly closed might not be added or returned to the pool.
You should add "Pooling = true" (and add a non-zero "Min Pool Size") to the connection string.
回答3:
Let the provider handle connection pooling for you; don't try to do better than it - you will fail.
With the default connection settings the provider will maintain a connection pool. When you close/dispose, the connection is actually just released to the pool. it is not necessarily really closed.
回答4:
By default, SqlConnections make use of connection pooling, which will allow the system to manage the re-use of previous connection objects rather than truly creating "new" connections for each request - up to a pool maximum value. And its built-in, so you don't really have to do anything to leverage it.
Writing your own pooling/connection manager is fraught with peril, and leads to all manner of evil, so it seems to me allowing the system to manage your connections from the pool is probably your best bet.
来源:https://stackoverflow.com/questions/12429519/obtaining-sql-connection-most-efficiently-when-using-asp-net-and-web-services