How do I treat the SQLiteCommand object,
do I have to call Dispose() after ExecuteScalar, ExecuteNonQuery and ExecuteReader or not?
The documentation example on SQLiteCommand doesn't dispose it whilst
in the SQLiteTransaction the example disposes the SQLiteCommand object.
I always close the data reader object though. My application accesses the db from many threads.
Mostly I am interested in not leaking connections or disturbing SQLite. I am aware of using and IDisposable usage
It's best-practise to dispose everything that implements IDisposable as soon as you're finished with it because it might use unmanaged resources.
This should be done with the using-statement since it wraps the code that uses this object and because it disposes it also in case of an exception.
using(var con = new SQLiteConnection(conString))
using(var cmd = new SQLiteCommand(con))
{
con.Open();
// ...
} // also closes the connection
If it is disposable, dispose it if you will not use it again.
The best would be, to use using
using(SQLiteCommand cmd as new SQLiteCoammand())
{
...
}
So it will be disposed automatically when leaving the using scope.
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 supress the call to the finalizer, making calling dispose a performance enhancement.
The using statement will call Dispose on an object even if an exception occurs that bypasses the code that calls Close(). This way you don't have to write a try/finally block just to close the readers or the connection. You also avoid this 1-in-100 case where you forget to write the proper finally block.
Such 1-in-100 cases have a tendency to occur much more frequently than one would think
Related
I am using "using" Keyword in c#.
using(SqlConnection sourceConnection = new SqlConnection())
{
sourceConnection.Open();
var destinationConnection = new SqlConnection();
destinationConnection.Open();
}
In Above line of code is both the connections will dispose or only sourceConnection() will dispose.
Only sourceConnection, i.e. the object that you wrap in the using statement, will be disposed. You should use another using statement to make sure that destinationConnection is also disposed:
using (SqlConnection sourceConnection = new SqlConnection())
using (var destinationConnection = new SqlConnection())
{
sourceConnection.Open();
destinationConnection.Open();
}
using operates on the IDisposable interface. Ignoring the scoping of the variable, it basically does something a bit like this:
SqlConnection sourceConnection = new SqlConnection();
try
{
sourceConnection.Open();
var destinationConnection = new SqlConnection();
destinationConnection.Open();
}
finally
{
if (sourceConnection != null)
{
sourceConnection.Dispose();
}
}
So in answer to your question, it will only close one.
From MSDN via this post by Robert S.:
C#, through the .NET Framework common
language runtime (CLR), automatically
releases the memory used to store
objects that are no longer required.
The release of memory is
non-deterministic; memory is released
whenever the CLR decides to perform
garbage collection. However, it is
usually best to release limited
resources such as file handles and
network connections as quickly as
possible.
The using statement allows the
programmer to specify when objects
that use resources should release
them. The object provided to the using
statement must implement the
IDisposable interface. This interface
provides the Dispose method, which
should release the object's resources.
Again this indicates that it only works on one object: the subject of the using.
As some people already noted, using wraps the IDisposable interface, as in:
using (var foo = new MyDisposable()) { ... }
is the same as:
var foo = new MyDisposable()
try {
...
}
finally {
if (foo != null) { foo.Dispose(); }
}
So far so good. The reason that C# implements this is because of unmanaged resources. Why? Unmanaged resources require you to clean up the stuff at a time you want, instead of a time that the Garbage Collector (GC) wants (which is f.ex. when you run out of memory).
Consider the alternative for a moment: let's assume you have a file. You open the file, write some bytes, forget 'close' and then don't have IDisposable to close it. Your file will continue to be open, even though you don't use the object anymore. Even worse, you don't even know that data has been written if your program exits. If your program runs long enough, at some point the GC will probably kick in and remove the thing for you, but until then every other attempt to open the file will probably give you a big, fat error. So, in short...: a lot of pain and misery.
And this is what IDisposable solves.
Connections, files, memory access, network access, ... basically everything that uses stuff that needs to be cleaned up implements IDisposable. It even holds true that if a type implements IDisposable, you'd better Dispose it.
So... SQL connections implement IDisposable, SQL Readers implement IDisposable, and so forth. Personally, I tend to check every type for the presence of an IDisposable interface, before working with it (so yeah that is: all the time).
Once you understand this, the correct way to use all this is obvious:
using (var sourceConnection = new SqlConnection())
{
sourceConnection.Open();
using (var destinationConnection = new SqlConnection())
{
destinationConnection.Open();
// ...
using (var myReader = srcConnection.ExecuteReader(...))
{
// ...
}
}
}
... and so on.
Now, in some cases you obviously cannot use using because you're using different methods. How to solve this? Easy: Implement the Dispose Pattern in the class that has these methods.
More information (as well as the Dispose pattern): https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx
Only one of them will be disposed, you're never explicitly calling Dispose or wrapping in a using the destinationConnection.
You could do this, and both will always dispose.
using(SqlConnection sourceConnection = new SqlConnection())
{
using(SqlConnection destinationConnection = new SqlConnection())
{
}
}
I am trying to test this piece of code by putting in breakpoints. I want to make sure that after the using block the dispose method is called and the resources (SqlCommand), is gracefully released.
However nowhere in the using block I hit any dispose?
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#OrganizationID", SqlDbType.Int);
command.Parameters["#OrganizationID"].Value = organizationId;
connection.Open();
SqlDataReader sqlDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
try
{
while (sqlDataReader.Read())
{
//do something
}
}
finally
{
sqlDataReader.Close();
}
}
The call to Dispose of IDisposable happens after the using block has finished execution, normally or abnormally (i.e. through an exception).
The only way you could catch the call in a source-level debugger is when you have the source code for your IDisposable - in your case it would be the source code of SqlCommand class.
One simple way of checking the way this works is to make your own IDisposable implementation, put it into a using block, and observe its behavior. The call to Dispose should follow immediately after completion of the using block.
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. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):
Key part is the "achieve the same result by putting the object inside a try block and calling finally".
SqlCommand command = new SqlCommand(queryString, connection);
try {
// your code here
} finally {
command.Dispose();
}
From MSDN
I am using Visual Studio's code analysis tool, and one of the warnings it gives me is "Do not dispose objects multiple times: Object 'conn' can be disposed more than once in method 'CycleMessages.discernScan_Reprint()'. To avoid generating a System.OjectDisposedEx you should not call Dispose more than one time on an object. Line:61
private void discernScan_Reprint()
{
try
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection("my constring");
using (conn)
{
SqlCommand cmd = new SqlCommand("usp_myproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
using(cmd)
{
cmd.Parameters.Add(new SqlParameter("#param", param));
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
conn.Close(); // this is line 61
}
}
switch(dt.Rows.Count)
{
default:
throw new Exception("message");
case 1:
//do Stuff
case 0:
//do stuff
break;
}
}
catch (Exception ex) {throw;}
}
I don't dispose the conn (explicitly via conn.Dispose();), I just close it and allow the using encapsulation to dipose of the conn object- I know I can allow it to be closed via the disposal, but why is it saying I'm disposing it twice? If anything it should warn me saying "You don't need to terminate connections on objects that will be disposed" or something like that. Am I missing something?
Edits:
From ref link on close...
The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled.
and
If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is closed.
I know that functionally Close() is the same as dispose, but that is not literal from my understanding. When I close the object it is not disposed. It is either closed or returned to the connection pool, disposing (again from my understanding) internally calls the close() methods- so while redundant, I still am baffled as to why it is explicitly saying it is already disposed, when it's not.
The Dispose pattern suggests that implementors provide synonyms for Dispose that make sense in the context of the object. One such synonym on SqlConnection is Close():
Close and Dispose are functionally equivalent.
Since you're explicitly calling Close(), and the object's Dispose() method is being called when the connection's using statement ends, you're effectively calling Dispose() twice.
The best approach is to just let the using block handle it for you, since it guarantees that Dispose() is called even when an exception occurs from inside the using block. It also sets the variable to null so that it can be GC'd as soon as possible.
Edits to respond to #alykin's questions
The documentation says that the Close() and Dispose() methods are functionally equivalent, but #alykin has identified a scenario where they don't actually do the same thing. If I'm reading her comment correctly, it works something like this:
The following works:
SqlConnection conn = GetConnSomehow();
SqlCommand cmd = conn.CreateCommand();
// ...
conn.Open();
cmd.ExecuteSomething();
cmd.Close();
// ... time passes ...
conn.Open();
The following doesn't:
SqlConnection conn = GetConnSomehow();
SqlCommand cmd = conn.CreateCommand();
using ( conn ) {
cmd.ExecuteSomething();
}
// ... time passes ...
// This won't compile, according to alykins.
conn.Open();
This shows that SqlConnection objects can be reused, at least when they've been only Close()'d.
Likely the reason why the second example with the using block doesn't compile is that the compiler knows that conn has been set to null when the using block ends, so it knows that you can't call methods on a null object reference.
I'm still not sure that this shows that a Dispose() is actually any different than a Close() though, since the incongruity arises due to the nulling semantic of the using block. It would be worthwhile testing whether or not an SqlConnection can be re-opened after it is Dispose()'d but not nulled. Even if it were, I wouldn't rely on that behavior since it is counter to Microsoft's own guidelines set in the Dispose Pattern documentation.
Additionally, I would not use the first block that doesn't use a using block - if an exception occurs, the connection may be leaked, or at least, held open for a non-deterministic amount of time until the GC sees that the object has been leaked and invokes its finalizer.
I would not rely on any difference in behavior between Close() and Dispose() - I would recommend against attempting to re-open a previously-closed SqlConnection object. Let the pooler handle actually keeping the connection alive even if you close or dispose the SqlConnection object you were handed.
A note on using statements.
Consider the following block of code:
IDisposable thing = GetThing();
using ( thing ) {
thing.DoWork();
}
That block of code is exactly identical to this block:
IDisposable thing = GetThing();
try {
thing.DoWork();
}
finally {
thing.Dispose();
thing = null;
}
And the following block, as considered by Microsoft, their documentation, and their analysis tools, counts as two disposes:
SqlConnection conn = GetConn();
using ( conn ) {
DoWork(conn);
conn.Close(); // code analysis tools count this as one Dispose().
} // implicit conn.Dispose() from the using block, so that's two.
Ignore the fact that Close and Dispose don't exactly do the same thing. They don't want you to rely on that, nor should you in case the behavior does actually get fixed.
It is informing you that the explicit close is disposing resources early. The using statement will automatically dispose it for you.
According to MSDN:
Close and Dispose are functionally equivalent.
Thus, calling .Close() disposes of the object. Additionally, since the object is in a using block, the compiler also calls .Dispose(). Only one of the two is needed. (And the latter is recommended in this case.)
Essentially, you just need to remove the call to Close() since the using block will handle that for you when it disposes of the object:
using (conn)
{
SqlCommand cmd = new SqlCommand("usp_myproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
using(cmd)
{
cmd.Parameters.Add(new SqlParameter("#param", param));
conn.Open();
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
}
}
close(); and dispose(); essentially do the same thing, that is why you are receiving this warning. Check this link for more information.
I'm using this code:
public void InsertMember(Member member)
{
string INSERT = "INSERT INTO Members (Name, Surname, EntryDate) VALUES (#Name, #Surname, #EntryDate)";
using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand(INSERT, sqlConnection))
{
sqlCommand.Parameters.Add("#Name", SqlDbType.VarChar).Value = member.Name;
sqlCommand.Parameters.Add("#Surname", SqlDbType.VarChar).Value = member.Surname;
sqlCommand.Parameters.Add("#EntryDate", SqlDbType.Date).Value = member.EntryDate;
sqlCommand.ExecuteNonQuery();
}
}
}
Is it wrong if I don't add sqlConnection.Close(); before disposing it? I mean. It's not showing any errors, no problems at all. Is it better to Close it first? If yes, why?
No need to Close or Dispose the using block will take care of that for you.
As stated from MSDN:
The following example creates a SqlConnection, opens it, displays some
of its properties. The connection is automatically closed at the end
of the using block.
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
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. MSDN
So ultimately your code line
using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
will be converted into a normal try finally block by compiler calling IDisposable object in the finally
According to MSDN documentation for the Close method:
you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.
Therefore, calling Dispose (implicitly so, even, using using) will cover your bases, as it were.
It's worth noting, too, I think,though not specific to your case, that Close will always effectively be called when the thing is wrapped in a using statement - which might not be the case should it be omitted and an exception occur without the proper try/catch/finally handling.
Is it wrong if I don't add sqlConnection.Close(); before disposing it
No, it is not as long as you are using your connection within Using. When you will leave the using scope, Dispose will be called for sql connection. which will close the existing connection and free-up all the resources as well.
The using statement is a try finally block and in your case the final block would have a connection.Dispose() call. So you don't really need a independent connection.Close() statement there.
The advantage is that this ensures the disposal even in case of an exception since the finally block will always run.
try
{
sqlConnection.Open();
// ....
}
finally
{
if(sqlConnection != null)
sqlConnection.Dispose();
}
You are using a Using which will Dispose() the object for you.
If you take the connection outside of the Using statement, then yes - you would need to close the connection when finished.
No, it is not wrong. The sqlConnection will close the connection after it will pass using block and call Dispose method. SqlConnection.Dispose() equal to SqlConnection.Close() method.
From MSDN: If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.
I've the following code
using(MemoryStream ms = new MemoryStream())
{
//code
return 0;
}
The dispose() method is called at the end of using statement braces } right? Since I return before the end of the using statement, will the MemoryStream object be disposed properly? What happens here?
Yes, Dispose will be called. It's called as soon as the execution leaves the scope of the using block, regardless of what means it took to leave the block, be it the end of execution of the block, a return statement, or an exception.
As #Noldorin correctly points out, using a using block in code gets compiled into try/finally, with Dispose being called in the finally block. For example the following code:
using(MemoryStream ms = new MemoryStream())
{
//code
return 0;
}
effectively becomes:
MemoryStream ms = new MemoryStream();
try
{
// code
return 0;
}
finally
{
ms.Dispose();
}
So, because finally is guaranteed to execute after the try block has finished execution, regardless of its execution path, Dispose is guaranteed to be called, no matter what.
For more information, see this MSDN article.
Addendum:
Just a little caveat to add: because Dispose is guaranteed to be called, it's almost always a good idea to ensure that Dispose never throws an exception when you implement IDisposable. Unfortunately, there are some classes in the core library that do throw in certain circumstances when Dispose is called -- I'm looking at you, WCF Service Reference / Client Proxy! -- and when that happens it can be very difficult to track down the original exception if Dispose was called during an exception stack unwind, since the original exception gets swallowed in favor of the new exception generated by the Dispose call. It can be maddeningly frustrating. Or is that frustratingly maddening? One of the two. Maybe both.
using statements behave exactly like try ... finally blocks, so will always execute on any code exit paths. However, I believe they are subject to the very few and rare situations in which finally blocks are not called. One example that I can remember is if the foreground thread exits while background threads are active: all threads apart from the GC are paused, meaning finally blocks are not run.
Obvious edit: they behave the same apart from the logic that lets them handle IDisposable objects, d'oh.
Bonus content: they can be stacked (where types differ):
using (SqlConnection conn = new SqlConnection("string"))
using (SqlCommand comm = new SqlCommand("", conn))
{
}
And also comma-delimited (where types are the same):
using (SqlCommand comm = new SqlCommand("", conn),
comm2 = new SqlCommand("", conn))
{
}
Your MemoryStream object will be disposed properly, no need to worry about that.
With the using statement, the object will be disposed of regardless of the completion path.
Further reading...
http://aspadvice.com/blogs/name/archive/2008/05/22/Return-Within-a-C_2300_-Using-Statement.aspx
http://csharpfeeds.com/post/8451/Return_Within_a_Csharp_Using_Statement.aspx
Take a look at your code in reflector after you compile it. You'll find that the compiler refactors the code to ensure that dispose is called on the stream.