If I have code with nested objects like this do I need to use the nested using statements to make sure that both the SQLCommand and the SQLConnection objects are disposed of properly like shown below or am I ok if the code that instantiates the SQLCommand is within the outer using statement.
using (var conn = new SqlConnection(sqlConnString))
{
using (var cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdTextHere;
conn.Open();
cmd.Connection = conn;
rowsAffected = cmd.ExecuteNonQuery();
}
}
Yes. You could clean it up a little like this
using (SqlConnection conn = new SqlConnection(sqlConnString))
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
// code here
}
But you would still want a using for each IDisposable object.
Edit: Consider this example of not using an inner using statement.
class A : IDisposable
{
public void Dispose()
{
Console.WriteLine("A Disposed");
}
}
class B : IDisposable
{
public void Dispose()
{
Console.WriteLine("B Disposed");
}
}
Code
using (A a = new A())
{
B b = new B();
}
At the end of the block, A is properly disposed. What happens to B? Well, it's out of scope and simply waiting to be garbage collected. B.Dispose() is not called. On the other hand
using (A a = new A())
using (B b = new B())
{
}
When execution leaves the block (actually, blocks), the compiled code executes calls to the Dispose() method of each object.
You can omit the using around the SqlCommand. The GC will eventually clean it up for you. However, I strongly advice you not to do this. I will explain why.
SqlCommand indirectly inherits from System.ComponentModel.Component, and it therefore inherits its Finalizer method. Not calling dispose on a SqlCommand will ensure that the command is promoted at least one generation after it goes out of scope (the .NET garbage collector is a generational gc). For instance: when the command was in gen 1, it will move on to gen 2. Finalizable objects are kept longer in memory to ensure the finalizer can safely run. But not only the command itself is kept in memory, but all the objects it references go with it to that generation. Objects that it will reference are the SqlConnection, the list of SqlParameter objects, the possibly large CommandText string, and many other internal object it references. That memory can only be removed when that generation is collected, but the higher the generation the less often it is swept.
Not calling will therefore give extra memory pressure and extra work for the finalizer thread.
When .NET is unable to allocate new memory, the CLR will force a garbage collect of all generations. After this, the runtime will usually have again enough space to allocate new objects. However, when this forced collect happens when there are a lot of objects in memory that still have to be promoted to a next gen (because they are finalizable, or are referenced by a finalizable object) it is possible that the CLR is unable to free up enough memory. An OutOfMemoryException will be the result of this.
I must admit I have never seen this happen, because developers didn’t dispose just their SqlCommand objects. However, I have seen OOMs in production systems a lot, caused by not disposing objects properly.
I hope this gives a little bit of background on how the GC works and what the risk is of not disposing (finalizable) object properly. I always dispose all disposable objects. While a look in Reflector could prove that this not necessarily for a certain type, this kind of programming leads to code that is less maintainable and makes code depend on internal behavior of a type (and this behavior might change in the future).
You should call dispose on both, however, it is easier to read if you just do this:
using (SqlConnection conn = new SqlConnection(sqlConnString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdTextHere;
conn.Open();
cmd.Connection = conn;
rowsAffected = cmd.ExecuteNonQuery();
}
since there's an implicit block created (like an if statement or for statement) and since using is an entire block, you don't need the braces and it looks neater in my opinion. Some will say you shoul always use braces because it's too easy to accidentally add a second statement and create a bug, but in this case i think that's unlikely.
To answer your question, yes, you can do that.
Since the SqlCommand object is limited by outer braces, it will be collected by GC when the execution goes out of the block.
Other answers are also okay, but they did not exactly answered your question :)
Related
I am the third generation to work on a system within my organization and of course there are differences in programming styles. I was wondering what the correct way of connecting to a database is as there are two different styles being used within the system. So whats the "correct" way?
Method 1:
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("StoredProcedure", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("foo", bar));
}
using (SqlDataReader reader = command.ExecuteReader())
{
//do stuff
}
}
}
catch (Exception ex)
{
//do stuff
}
Method 2:
// Variables
SqlCommand loComm;
SqlConnection loConn = null;
SqlDataReader loDR;
try
{
// Init command
loComm = new SqlCommand("foo");
loComm.CommandType = CommandType.StoredProcedure;
loComm.Parameters.AddWithValue("foo", bar);
// Init conn
loConn = new SqlConnection(String);
loConn.Open();
loComm.Connection = loConn;
// Run command
loDR = loComm.ExecuteReader();
//do stuff
}
catch (Exception ex)
{
//do stuff
}
While both methods work I am not sure which one is the most appropriate to use. Is there a reason to use one over the other? The second method is cleaner and easier to understand to me, but it doesn't automatically run the iDispose() function when it is finished.
Edit: My question is different then the one suggested, because one approach uses the "using" statement while the other doesn't. So my question is directly related to whether or not to utilize the "using" statements when making a database connection.
Thanks, for all the responses.
Method 2 is simply incorrect and should be repaired.
When completed, you will be left with IDisposable instances that have not been disposed. Most likely, this will play havoc with the connection management that goes on behind the scenes with SqlConnection, especially if this code gets thrashed a lot before GC decides to step in.
If an instance is IDisposable, then it needs to be Disposed of, preferably in the smallest scope possible. Using using will ensure that this happens, even if the code malfunctions and exceptions are thrown.
A using statement:
using(var disposableInstance = new SomeDisposableClass())
{
//use your disposable instance
}
is (give or take a few minor details) syntactic sugar for:
var disposableInstance = new SomeDisposableClass();
try
{
//use your disposable instance
}
finally
{
//this will definitely run, even if there are exceptions in the try block
disposableInstance.Dispose();
}
Even if something goes wrong in the try block, you can be assured that the finally block will execute, thereby ensuring that your disposables are disposed, no matter what happens.
In the first example, if there is an exception thrown, the objects wrapped in the using blocks will be properly closed and disposed.
In the second, you will manually need to dispose of your objects.
One other thing worth mentioning is that if you were planning on disposing of your objects only when an exception is thrown, you will have objects that are not disposed of, so you would need to implement a try..catch..finally and dispose the objects within the finally block.
The first is the better option.
The first one will close the connection if an exception is thrown.
The second one won't, so I'd say go with the first choice.
What the using block does is to warranty that the object Dispose method will always be invoked, no matter if an exception is thrown or not.
Dispose is a method used to clean up resources. In the case of a DB connection, the connection is released, which is really important.
So, the correct way in this case is using the using pattern.
The object included between the using parents mus be IDisposable whic means that it has a Dispose method that should be invoked when the object is no longer needed. If you don't invoke dispose, it will be disposde at any indeterminate time, when the garbage collector destroys the object. That's undesirable in case like a DB connection that must be closed as soon as possible.
The equivalen of usin is a try finally, which includes a call to Dispose within the finally block.
Reading here, it says:
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned. The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
That sounds like the correct way is method 1.
According to MSDN If the IDisposable resource of the
nested inner using statement contains the resource of the outer using
statement, the Dispose method of the nested resource releases the
contained resource.
MSDN (http://msdn.microsoft.com/en-us/library/ms182334.aspx) =>
Example Nested using statements (Using in Visual Basic) can cause
violations of the CA2202 warning. If the IDisposable resource of the
nested inner using statement contains the resource of the outer using
statement, the Dispose method of the nested resource releases the
contained resource. When this situation occurs, the Dispose method of
the outer using statement attempts to dispose its resource for a
second time. In the following example, a Stream object that is created
in an outer using statement is released at the end of the inner using
statement in the Dispose method of the StreamWriter object that
contains the stream object. At the end of the outer using statement,
the stream object is released a second time. The second release is a
violation of CA2202.
But if i try this piece of code the code still works and returns the number count inserted into the table. Which is contradictory towards the MSDN explanation. I would expect the code to crash on the cmd.ExecuteScalar() call because the conn variable is disposed after the first inner using statement.
Why is this still working and why isn't the conn variable disposed after the first inner using?
static void Main(string[] args)
{
var numbers= DoItGetIt();
}
private static int DoItGetIt()
{
using (var conn = new SqlConnection("Data Source=BestmixSql;Initial Catalog=Test;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO [Test].[dbo].[Tabel] VALUES (666)";
cmd.ExecuteNonQuery();
}
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT(*) FROM [Test].[dbo].[Tabel]";
var count = cmd.ExecuteScalar();
return Convert.ToInt32(count);
}
}
}
The MSDN example you are talking to is specifically talking to the scenario where the inner object takes posession of the outer object; for example, a StreamWriter can assume responsibility for a Stream. In that scenario, disposing the inner object also causes the outer object to be disposed - but this is not true in the general case.
In particular, a command does not assume responsibility for disposing a connection. Interestingly, a data-reader can assume responsibility, but only via an optional flag.
Many such objects offer flags to let the caller determine whether the inner object should assume responsibility for disposing the outer object. For example, StreamWriter also now offers a constructor-overload with a bool leaveOpen parameter. If you pass this as true, the StreamWriter does not cascade the Dispose().
This is all implementation details of the inner object, when it is specifically written to do this. It is not a default behaviour of the using pattern.
Side note: I would say MSDN is simply wrong here. The correct implementation is the first sample with two using. The second example is non-intuitive, and prone to incorrect implementation. Don't use it. If necessary, use leaveOpen to make is explicit, but frankly it usually works fine without this, if you are about to dispose it anyway.
I keep finding conflicting results for this question. Let's look at this C# code of running an SQL query:
using (SqlConnection cn = new SqlConnection(strConnectString))
{
cn.Open();
using (SqlCommand cmd = new SqlCommand(strSQL, cn))
{
cmd.ExecuteNonQuery();
}
//Do I need to call?
cn.Close();
}
Do I need to call that last cn.Close()? The reason I'm asking is that in a heavy traffic web app I run out of connections in a pool.
The using keyword as used here:
using (SqlConnection cn = new SqlConnection(strConnectString))
{
// Stuff
}
is short for:
SqlConnection cn = null;
try
{
cn = new SqlConnection(strConnectString);
// Stuff
}
finally
{
if (cn != null) cn.Dispose();
}
cn.Dispose() will be called immediately after cn goes out of scope of the using, which in turn immediately closes the connection (because SqlConnection.Dispose() does just that).
UPDATE
This should not be confused with garbage collection. GC is non-deterministic in .NET, which is exactly why the IDisposable inteface and Dispose Pattern were introduced. IDisposable allows expensive resources to be released in a timely, deterministic manner.
Not necessary to close it if you use using as it calls Displose() internally.
Here's a bit details about using keyword in ADO.NET, might be worth reading.
Leveraging the "using" keyword in C#
A quick search #SO will lead you to this post, where you can find your answers there too.
You dont need to close the connection when you use the Using statement.
Scott hanselman explains it here Why The Using Statement Is Better Than A Sharp Stick In The Eye And A SqlConnection Refactoring Example.
In a heavy traffic web app I run out of connections in a pool.
Make sure you are using the same connection string this way SQL will use Connection Pooling.
is the connection closed immediately, or is it closed when the garbage
collector gets to it
Edit:
The Dispose pattern is used to provide deterministic destruction of resources. Since the .net runtime garbage collector is non-deterministic (which means you can never be sure when the runtime will collect old objects and call their finalizer). Therefore, when you implement the Dispose pattern properly you provide deterministic release of the resources and in cases where the consumer is careless and does not dispose the object, the finalizer will clean up the object.
The database access classes that implement IDbConnection, IDbCommand and IDataReader all implement IDisposable, but obviously the Command and the Reader are dependent on the Connection. My question is, do I have to Dispose() of each these objects individually or will disposing of the Connection object dispose of the others too ?
That is, can I do this and guarantee I'm not risking leaving any unmanaged resources not being freed:
using (IDbConnection conn = GetConnection())
{
IDbCommand cmd = conn.CreateCommand();
cmd.CommandText = " ..... ";
IDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
}
}
Or do I have to do this instead:
using (IDbConnection conn = GetConnection())
{
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = " ..... ";
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
}
}
}
}
Or is this implementation dependent, so it would potentially work using one database's provider but not for another's ?
Best policy is to use all ADO.NET objects in using blocks- full stop.
A little Reflector-ing on various ADO.NET objects shows that things will more or less be dropped on the floor if not Closed/Disposed. The effect of that will depend a lot on which providers you're using- if you're using something with unmanaged handles underneath (ODBC, OleDb, etc), you're probably going to leak memory, as I didn't see anything in the way of finalizers. If it's an all-managed provider (eg, SqlClient), it'll eventually get cleaned up, but depending on which objects you're holding onto, you could end up keeping resources in use on the DB server a lot longer than you want.
You should dispose them individually or you could also use the solution provide here.
Dispose of them individually. It's entirely possible that the Reader and Command objects do more in their dispose routines than just destroy the connection (either now or in a future version of ADO.NET). So to (a) be explicit and (b) be safe you should dispose of them all individually.
The fact that they implement IDisposable suggests that you should always run the Dispose routine when you're finished with the object, so it's best not to try and second guess the interface, it won't give you any benefit, and you'll probably end up leaking memory and handles.
There are things you can do though to make your code look cleaner when nesting using statements. For example:
(using SqlConnection conn = new SqlConnection())
(using SqlCommand comm = new SqlCommand())
{
//Do stuff
}
That looks neater (in my opinion) than nesting braces.
You should dispose them individually. Even if disposing the IDbConnection would dispose everything under the covers (I don't know if it actually does, nor do I care, for the reason that follow), you should program in the future tense. Tomorrow somebody will edit that code and issue a new command on the same connection and then it will wonder why is he getting an error that the connection is still in use (because the IDataReader was no disposed).
The main advantage of the using statement is resources releasing management. Usually, the .NET Framework Garbage Collector controls resources allocation and release. With the using statement, we can take the control of it. So a using statement implements an IDisposible interface which contains a public Dispose() method.
Also you can always call a Dispose() method manually to release a resource or an object from memory.
hope this helps.
I usually use code like this:
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
{
var command = connection.CreateCommand();
command.CommandText = "...";
connection.Open();
command.ExecuteNonQuery();
}
Will my command automatically disposed? Or not and I have to wrap it into using block? Is it required to dispose SqlCommand?
Just do this:
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
using(var command = connection.CreateCommand())
{
command.CommandText = "...";
connection.Open();
command.ExecuteNonQuery();
}
Not calling dispose on the command won't do anything too bad. However, calling Dispose on it will suppress the call to the finalizer, making calling dispose a performance enhancement.
The safest policy is to always call Dispose() on an object if it implements IDisposable, either explicitly or via a using block. There may be cases where it is not required but calling it anyway should never cause problems (if the class is written correctly). Also, you never know when an implementation may change meaning that where the call was previously not required it is now definitely required.
In the example you've given, you can add an extra inner using block for the command, as well as maintaining the outer using block for the connection.
Yes, you should, even if it the implementation is currently not doing much, you don't know how it is going to be changed in the future (newer framework versions for instance). In general, you should dispose all objects which implement IDisposable to be on the safe side.
However, if the operation is deferred and you don't control the full scope (for instance when working asynchroneously, or when returning an SqlDataReader or so), you can set the CommandBehavior to CloseConnection so that as soon as the reader is done, the connection is properly closed/disposed for you.
In practice, you can skip Dispose. It doesn't free any resources. It doesn't even suppress finalization since the SQLCommand constructor does that.
In theory, Microsoft could change the implementation to hold an unmanaged resource, but I would hope they'd come out with an API that gets rid of the Component base class long before they'd do that.
You can find out this kind of stuff using Reflector or dotPeek or https://referencesource.microsoft.com/.
I had a small dig (I would suggest that you dig yourself though to be fully sure of the rest of this though as I didn't try that hard) and it looks like when you kill a connection there is no disposal of any children associated with that connection. Furthermore it doesn't actually look like the disposal of a command actually does that much. It will set a field to null, detach itself from a container (this may prevent a managed memory leak) and raise an event (this might be important but I can't see who is listening to this event).
Either way it's good practice to use this stuff in a using block or to ensure you dispose of it using a dispose pattern in the object that holds the connection (if you intend to hold onto the command for a while).
In my opinion, calling Dispose for both SqlConnection and SqlCommand is good practice, use below code
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
try{
using(var command = connection.CreateCommand())
{
command.CommandText = "...";
connection.Open();
command.ExecuteNonQuery();
}
}
catch(Exception ex){ //Log exception according to your own way
throw;
}
finally{
command.Dispose();
connection.Close();
connection.Dispose();
}