I don't get what is the syntax difference between regular connection and connection pool.
When I'm using the using key such as:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
command.ExecuteNonQuery();
}
Is this the way to perform a connection pool?
You can read about connection pooling here.
Basically, as long as the connection string is the same (including case), connections will be taken from the same connection pool.
You do not control the connection pool with connections but with the connection string. Most ADO providers use pooling per default.
The using statement is used to call the Dispose method of the object (in this case the connection class). By doing so, the connection is either returned to the pool or being disconnected depending of the connection string configuration.
You should also be aware of that connections are not returned to the pool directly if distributed transactions are being used (TransactionScope in .Net 4). The connections are returned when the transaction have been completed/rolled back.
If you are not using using, you should make sure that you call Connection.Close() as soon as possible. Especially if your application is under some form of load.
The management of connection pool is abstracted away from you using SqlConnection like in the above. By default in ADO.NET connection pool is turn on and you can further control that such as turning it off or controlling the pool size in the connection string e.g.
Turn off
Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Pooling=false;
or controlling min and max
Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Min Pool Size=5; Max Pool Size=20;
More details explanation and way to verify the pool
http://www.codeproject.com/KB/dotnet/ADONET_ConnectionPooling.aspx
as far as i know,
connection pooling is managed by ado.net client, since making connections to db is costly operation. ado.net makes pool of connections and whenever you need a connection it tries to give it from pool. even if you say to client code to close connection, ado.net hold that connection for later use. you dont manage the pooling
connection pool is told in web.config file of application. when you use using statements , you tell that object should be disposed end of using.
The SQL connection defaul is connection pooling.
(Max Pool Size=100)
You can config you connection pool from connection string.
You can find more informamtion about connection string from here.
Related
I want to use a connection pooling in my C# project. I understand that one I get the connection to the SQL server, while I'm using the same connection string, the cash pooling will work.
However I have doubts about: how is the best practice to pass the connection string through my different classes? Should I pass the connection string as a parameter to the methods that use it to connect? (for instance each time that I need to do a query)
ADO.NET has built-in connection pooling, and you can't really build a better one.
When you create a connection using a connection string, the Framework checks the connection pool to see if a connection with that connection string is available. If one is, it pulls it from the pool and returns it to you; otherwise, it creates a new one and returns that to you.
Similarly, when you close (dispose of) a connection, it is not immediately destroyed.
When you close a connection with a specific connection string, it is not immediately destroyed. Instead, it is released back into the connection pool.
Automatic connection pooling can be disabled, so that you could roll your own solution, but it's not advisable.
EDIT:
As pointed out, I didn't answer the question in my original answer.
In general, you don't pass connection strings around. Instead, they are stored in a configuration file (either web.config or app.config), in the connectionStrings section. When you need a connection string, you retrieve it within the method that requires it using ConfigurationManager.ConnectionStrings.
I don't get what is the syntax difference between regular connection and connection pool.
When I'm using the using key such as:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
command.ExecuteNonQuery();
}
Is this the way to perform a connection pool?
You can read about connection pooling here.
Basically, as long as the connection string is the same (including case), connections will be taken from the same connection pool.
You do not control the connection pool with connections but with the connection string. Most ADO providers use pooling per default.
The using statement is used to call the Dispose method of the object (in this case the connection class). By doing so, the connection is either returned to the pool or being disconnected depending of the connection string configuration.
You should also be aware of that connections are not returned to the pool directly if distributed transactions are being used (TransactionScope in .Net 4). The connections are returned when the transaction have been completed/rolled back.
If you are not using using, you should make sure that you call Connection.Close() as soon as possible. Especially if your application is under some form of load.
The management of connection pool is abstracted away from you using SqlConnection like in the above. By default in ADO.NET connection pool is turn on and you can further control that such as turning it off or controlling the pool size in the connection string e.g.
Turn off
Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Pooling=false;
or controlling min and max
Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Min Pool Size=5; Max Pool Size=20;
More details explanation and way to verify the pool
http://www.codeproject.com/KB/dotnet/ADONET_ConnectionPooling.aspx
as far as i know,
connection pooling is managed by ado.net client, since making connections to db is costly operation. ado.net makes pool of connections and whenever you need a connection it tries to give it from pool. even if you say to client code to close connection, ado.net hold that connection for later use. you dont manage the pooling
connection pool is told in web.config file of application. when you use using statements , you tell that object should be disposed end of using.
The SQL connection defaul is connection pooling.
(Max Pool Size=100)
You can config you connection pool from connection string.
You can find more informamtion about connection string from here.
I'm unsure at which level the connection pool is implemented in .NET.
When I call
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
Am I surely opening a new connection? Or could I possibly be reusing an active connection?
The connection pool present in SqlConnection can be absent in other DbConnection implementations?
Connection pooling happens automatically, unless you specify otherwise. If you scroll down to the section "Controlling Connection Pooling with Connection String Keywords" in the first link below, you'll see that the default for "pooling" is true.
http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx
Connection pools get created without any intervention by you, as long as the connection string is exactly the same (uppercase/lowercase matters in this point.)
The same can be said for the OleDbConnection and Connection Pooling.
http://msdn.microsoft.com/en-us/library/ms254502.aspx
I'm not using LINQ-to-SQL or Entity Framework bits in a web app, and have currently been using something like this (this is for a class project):
using System.Data;
using System.Data.SqlClient;
namespace StackOverflowClone.Models
{
public class Database
{
public static SqlConnection ActiveConnection { get; private set; }
static Database()
{
ActiveConnection = new SqlConnection(
"Data Source=********.database.windows.net;" +
"Initial Catalog=EECS341;Uid=*****;Pwd=*******;" +
"MultipleActiveResultSets=True;");
ActiveConnection.Open();
}
}
}
However this seems to cause threading issues because the static initializer runs once per server process, rather than once per request.
Does the framework provide a built in method of handling this or should I just have a function that coughs up database connections new'd up each time?
or should I just have a function that coughs up database connections new'd up each time?
Yes, do this. Let ADO.NET connection pooling handle the details for you. Your goal should be to keep the connection open for as short a period of time as possible.
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.
So, create a static GetConnection() method that returns a new open connection. Use this within a using statement so it can be closed and returned to the connection pool as soon as possible.
using(var cn = Database.GetConnection())
{
//query your data here, Dapper example below
cn.Execute("update MyTable set MyField = #newValue", new {newValue});
}
Always create new connections and destroy them with using. They are not really created from scratch, they are fetched from a connection pool. There is no performance penalty. Actually that's the best and correct way to go.
See my answer about using: https://stackoverflow.com/a/9811911/290343
Does the framework provide a built in method of handling this or
should I just have a function that coughs up database connections
new'd up each time?
Both, actually.
The web server is multi threaded, so each thread needs its own database connection. Just create one when needed.
The actual connections to the database are pooled. When you dispose a connection object, the actual connection isn't closed, but returned to the pool. If you create a new connection object with the same connection string, it will just reuse a connection from the pool.
We have some client code which is using the SqlConnection class in .NET to talk to a SQLServer database. It is intermittently failing with this error:
"ExecuteReader requires an open and available Connection. The connection's current state is Closed"
The "temporary" solution is to reboot the process, after which everything works - however, that's obviously unsatisfactory.
The code is keeping a cache of SqlConnection instances, one for each database.
We'd like to re-write the code, but before I do, I need to know a few things:
My first question is: Is it inefficient to repeatedly connect and disconnect SqlConnection objects, or does the underlying library perform connection pooling on our behalf?
// Is this bad/inefficient?
for(many-times)
{
using(SQLConnection conn = new SQLConnection(connectionString))
{
// do stuff with conn
}
}
Because our code does not do the above, what seems the likely cause of the problem is that something happens to the underlying SQLServer database during the "lifetime" of the connection that causes the connection to be closed...
If it turns out that it is worthwile to "cache" SqlConnection objects, what is the recommended way to handle all errors that could be resolved simply by "reconnecting" to the database. I'm talking about scenarios such as:
The database is taken offline and brought back online, but the client process had no open transactions while this was happening
The database was "disconnected", then "reconnected"
I notice that there is a "State" property on SqlConnection... is there an appropriate way to query that?
Finally, I have a test SQLServer instance set up with full access rights: how can I go about reproducing the exact error "ExecuteReader requires an open and available Connection. The connection's current state is Closed"
No, it's not inefficient to create lots of SqlConnection objects and close each of them when you're done. That's exactly the right thing to do. Let the .NET framework connection pooling do its job - don't try to do it yourself. You don't need to do anything specific to enable connection pooling (although you can disable it by setting Pooling=false in your connection string).
There are many things that could go wrong if you try to cache the connection yourself. Just say no :)
You should enable connection pooling on your connection string. In that case the runtime will add back your connections to the 'pool' when you close them, instead of really disconencting. When a 'new' connection is taken out of the pool it will be reset (ie. sp_reset_connection is called ) then presented to your application as a brand new, fresh connection. The pool is handling transparently such cases as if the connection is closed while idling in the pool.
The cost of creating a new connection 'from scratch' is significant because the authentication requires several roundtrips between client and server (depending on the authentication method and on SSL settings it can be 1 roundtrip in best case vs. about 10 in worse).
And to answer your question, connection raise the OnStateChange event when their state changes, but you shouldn't care about this if you use the pooling.
In my recent experience if you use this code:
using(SQLConnection conn = new SQLConnection(connectionString))
{
// do stuff with conn
}
have an error, and do not explicitly close the connection, it will not be closed or checked back into the pool. So use a catch or finally block to close the connection