Remembering SQL connection state in .net? - c#

Beside's the old known fact that connection.Close() vs connection.Dispose() are the same - except that running Close() over a disposed connection raises an exception while running Close() over a closed connection - is OK - I still have a question :
Assuming connection pooling is on , (default) - why is it important to remember the state of the connection ?
I've read this question here which shows that - avoiding opening and closing a connection saves performance.
This seems logic , but the problem is that the connection is never actually closed ! it is only marked for close.
Even If I use it under a using scope - the dispose just closes the connection and put it back in the pool.
Even if I wanted , I couldn't leave it open ( because I'd want others to use it). so I had to close/dispose it.
Looking at Dapper which also implements this behavior:
public static async Task<IEnumerable<T>> QueryAsync<T>(this...)
{
//...
bool wasClosed = cnn.State == ConnectionState.Closed;
using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
{
try
{
if (wasClosed) await ((DbConnection)cnn).OpenAsync()...
//...
}
finally
{
if (wasClosed) cnn.Close();
}
}
}
As you can see the "memorization" is implemented here.
nb , I already asked Marc about a related topic which is - why in dapper samples he uses both GetClosedConneciton and GetOpenConnection and I got an answer which is to show - that Dapper can deal with both scenarios. However this current question is about why it is re-set the connections state.
Question :
Looking at Dapper code it seems that it remembers the state and re-set the state after operation. ( I also know this behavior from the old sqldataadapter class)
The question is - why ? If I got a closed connection - then, I need to open it. great. but why do I have to close it by condition ? why not ALWAYS close it ? it's not going to hurt performance since the connection is not actually closed - it is only returned to pool.
The other way around - If I got an open connection , then I'd do work and keep it open (huh??)
AS you probably see , I'm missing something here. can someone please shed light ?

why not ALWAYS close it ?
The user could be doing lots of work on that connection. It could be associated with a transaction (closing would orphan it). It could have temporary tables (closing would destroy them), or other connection-preserved state (SET options, impersonation, etc).
Closing a connection here (if it was open originally) would be an unusual and unexpected thing with multiple nasty side-effects.

If you're writing a library function where it makes sense for the consumers to pass you a connection object (of whatever flavour) then the safest thing to do is to respect that connection:
if you're passed an open connection object, make no assumptions about it and certainly don't close it after you've completed your work - you don't know what your consumers have done with it or will do with it.
if you're passed a closed connection object, then you'd better open it before you attempt to use it, and you ought to close it after you're done - you know that your consumer can't have e.g. a transaction open against a closed connection.
If your code creates a connection object, then I'd always recommend that the creation be placed in a using statement and so it will always be closed when you're done.
So, the only remaining thing I can think to say is to think carefully about writing your functions and work out whether it makes sense for your consumers to be passing you connection objects - if your work should always be performed in isolation, it would make more sense to ask for e.g. a connection string and for your code to entirely control the connection.

Related

Connection stays open after using dbContext in .Net

After I use
using (TestDatabaseEntitites ctx = new TestDatabaseEntitites())
{
....
}
I want all my sql connections to close after the using statement and I think that is what's expected. But it doesn't happen. Even after ctx.Dispose().
The only way I can close all the open connections is clearAllPools method.
Am I doing something wrong?
Thanks.
Connection pool connections in .Net stay open behind the scenes by design. The reason for this is that opening a connection to the database is generally a very expensive operation which would take literally seconds.
For this reason, closing a connection will only reset it, so that a future Open will simply be passed the old reset connection instead of opening a new one.
This answer is referred from here
DbContext is a very light-weight object.
It doesn't matter whether your DbContext stays alive or you instantiate it just before making the call because the actual DB Connection only opens when you SubmitChanges or Enumerate the query (in that case it is closed on end of enumeration).
In your specific case. It doesn't matter at all.

Having sql connection open for a long time

I'm writing a program that generates Sitemaps. To avoid duplicates I'm using MSSQL Server to store links that are found. during this process It may read and write millions of links and the process of reading and writing may have very little gaps between them (I mean the time between each access to database is very tiny).
I want to know If I can open the connection when the program starts and close it at the end. please consider that creating some sitemaps may take days to finish. Or is it wise to open and close connection each time I want to access the db?
By the way, I'm using sql server locally.
The answer to your question is the Connection Pooling feature.
It is always preferable to open the connection just when needed, access your data, close and dispose the connection immediately
Indeed a specific work pattern exists
using(SqlConnection con = new SqlConnection(.....))
{
... do your work with the database here ....
}
The using statement ensures that the object created at the opening is closed and disposed at the closing braces. Even if an Exception occurs in database code.
This doesn't mean that you cannot try to optimize your code. For example you could gather a few of sitemaps together and write them in just one shot, but usually it is best to follow a simple work pattern, finish the work as soon as possible and worry for optimization later.
You can work with the following code :
SqlConnection conn;
try
{
conn = new SqlConnection(_dbconnstr));
}
catch
{
//exceptions are bubbled
throw;
}
finally
{
//Dispose is always called
conn.Dispose();
}
hope this helps!
I usually open and close connection each time I use it.
Releasing resources must be done when there is many connections around.
If you are the only one, you might keep your resources.
Be aware of setting timeout connection.
Good luck guy!
It is better to open/close the connection. There is no benefits in kipping connection open. ADO.NET Connection pooling (which is on by default) will take care of which connection to close and when.
From MSDN
CAUTION It is recommended that you always close the Connection when
you are finished using it in order for the connection to be returned
to the pool. This can be done using either the Close or Dispose
methods of the Connection object. Connections that are not explicitly
closed might not be added or returned to the pool. For example, a
connection that has gone out of scope but that has not been explicitly
closed will only be returned to the connection pool if the maximum
pool size has been reached and the connection is still valid.
If you know it's going to take a while, what about writing to a local data table and then when you reach a threshold, write all the records to the database.
Or even write the info to a local file (format of your choice) and then write that file to the database in one shot (or multiple shots if you want to do it every x records or y minutes.)

c# connection to database

I was wondering if it is a good idea to maintain a database connection ( System.Data.SqlClient.SqlConnection() ) open or is it recommended to close the connection after using it and open it again when needed ? ( Note : My app will run continuously for days/months ) . I am kind of pushed towards leaving it open. Which solution is better ?
In general, dispose of it when you're done with it, and don't worry about it.
ADO.NET implements connection pooling by default, so the connection is kept open behind the scenes so as to spare you the performance penalty of opening new connections all of the time.
Another reason to close the connections in your code -- if you lose connectivity to your database server when you're not using the connection, you won't encounter an error, which could happen if you keep the connection open.
You absolutely should open your connections as late as possible, and close them as soon as possible.
Not only should you close them when you are done, though: you should close them even between closely-related commands, if there is any other code running in between at all. In fact, let me put it like this: Close your ADO.NET Connection objects as quickly and frequently as you practically can. (that is, don't do obviously stupid things to close connections that obviously should not be closed)
By default, the ADO.NET provider for SQL Server (as well as most of the other prominent providers) provide connection pooling. This will actually manage the creation and destruction of these connections for you - but only if you close them when you are done.
If you wrap the creation and use of your connection objects in using blocks, this is easy to do...
using(SqlConnection conn = new SqlConnection(...))
{
///Open and use the connection
} //the 'using' causes it to automatically be closed.
Open the connection if you needed, don't waste resources ;-)

How does the SQL connection in an application should be called?

Back to basics.
I have an application written in c# and I am using the sqlClient to connect to database.
I have several methods and I usually open the connection in a try catch block
try{
**open connection**
//Mehod1()
//Method2()
........
}catch(exception){
//Do something
}finally{
**close connection**
}
The Problem is that there are a lot connections in pool.
I am using master page and in master page I am loading the menu from database (different menu for each user).
Then in main pages I open again a connection to get the rest data.
In the middle of the page it may be a method that need again to connect to database.
My Question is
Is this a good practise?
Am I doing something wrong?
Is there a better practise to avoid multiple connections?
What about singleton pattern?
Thanks in advance
SOLUTION
I found the reason!!!
I had forgot to close a connection.
I was sure that I had close it, but
sometimes you can't be so sure.
Thanks everyone for your responses
Since the connection is pooled you don't need to "reuse" it in different methods.
I use the following code:
using(SqlConnection connection = new SqlConnection("your-connectionstring"))
{
// Do your stuff here...
}
Using is just a short hand way of writting try-catch-finally. It is used for disposable objects.
And this can go into each method.
EDIT: Using the connection from the pool is not hurting performance either. All connection information are cached anyway. So just use the SqlConnection on an atomic level.
It's a good thing though to have the ConenctionString handling in a more generic way...
Using() as said above is a good way to new up a new object of a class that implements IDisposable. But with that being said , you cannot leave you connection open once you done. You have finite number of connection in the pool and leaving a connection unclosed can starve other SPIDs which are waiting for active connection which will finally timeout. So you should
Always have atomic and small transactions .
Close when done.
There is DAAB (data access application block) from Microsoft Enterprise Library which can be used as helper to open and close connections + do many other DB related tasks easily. Here it is
http://msdn.microsoft.com/en-us/library/cc511547.aspx
Probably you didn't dispose your SqlConnections
try this:
using (SqlConnection connection = new SqlConnection(connectionString))
{ }
this syntax will call method Dispose() automatically for you. Using statement details here
UPDATE:
A bit more info about this methods you may find here: Close, Dispose
Basically the difference is that method Dispose() called method Close(), but before it is cleaning some resources and removing connection from the pool details here.
As you see Dispose() doing a bit more than Close(). So if you going to reuse connection later use method Close() if not destroy that completely using method Dispose() which is automatically getting called if you using the syntax above.

Why Not Close a Database Connection in a Finally Block

Major Edit:
I misread the article! The comment was in regards to the finalize method of the the class not the finally block :). Apologies.
I was just reading that you should not close or dispose a database connection within a finally block but the article did not explain why. I can not seem to find a clear explanation as to why you would not want to do this.
Here is the article
If you look around, closing the connection in the finally block is one of the recommended ways of doing it. The article you were looking at probably recommended having a 'using' statement around the code that used the connection.
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "select * from someTable";
// Execute the query here...put it in a datatable/dataset
}
The 'using' statement will ensure the Connection object gets disposed immediately after it's needed rather than waiting for the Garbage Collector to dispose of it.
I have to disagree that you should not close or dispose of a database connection within a finally block.
Letting an unhandled (or even handled for that matter) exception leave open connections can take down a database pretty quickly if it has a lot of activity.
Closing a database connection is the defacto example of why to use the finally statement, IMHO. Of course, the using statement is my preferred method, which is maybe what the original author was going for.
Edit to the Major Edit:
That makes sense now. You wouldn't want to leave closing your database connection up to the garbage collector.
Without the original article, I can't speak for the author. However, depending on how you've implemented instantiating and opening the connection in relation to your try/catch/finally block, you might need to do some additional checking before just calling close. Ex, ensure the connection is not null and not already closed.
EDIT: The article says not to dispose of a connection object in your Finalize method, not to not close it in the finally block. In fact, in the paragraph above it says you should always be closing your connection after you use it, so it is returned to the connection pool.
"CAUTION It is recommended that you always close the Connection when you are finished using it in order for the connection to be returned to the pool. This can be done using either the Close or Dispose methods of the Connection object. Connections that are not explicitly closed might not be added or returned to the pool. For example, a connection that has gone out of scope but that has not been explicitly closed will only be returned to the connection pool if the maximum pool size has been reached and the connection is still valid.
Note Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition. For more information, "
http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.71).aspx?ppud=4
A little bit of Googling turns up quite a few pages that hold the opposite opinion. Using a "finally" block seems like a good way to ensure that the connection is always closed correctly, although as others have said I'd be interested to see the original article that said it wasn't a good idea.
From what I can see in the article it advices against calling Dispose or Close in the Finalizer of a class, not against doing so in a finally block, which is quite a different thing.
The Close method puts the connection object into a state from which it can be re-opened. The Dispose method puts it into a state from which it cannot be re-opened (closing it first if currently open).
If you instantiate a connection, open it, use it, then throw it away (the normal usage pattern), then a using block is the best and simplest way to do it.
Obviously, if you are doing something more complex with multiple Open and Close calls, then disposing it will throw a spanner in the works.

Categories

Resources