Nested Using Keyword for connection dispose. - c#

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())
{
}
}

Related

Code Analysis tool

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.

Why is the Destructor not being called?

I have a very interesting scenario where I would like a class to inform another entity it has been destroyed; however, its not doing what I want it too.
The Problem
The deconstructor, for some reason does not do what its supposed to do.
The Question
Why is the destructor not being invoked and make sure that it does do its necessary clean up.
The Code
So here we have the informer ~
class Connection
{
public const int Port = 50000;// Can be any range between 49152 and 65536
//Teh Constructor
public Boolean Connect()
{
//SetInformation
Information.Id = 545;
using (var WebServ = new ClientSDKSoapClient("ClientSDKSoap"))
{
ContinueConnection.WaitOne();
WebServ.ClientLogin(Information);
}
return true;
}
~Connection()
{
using (var WebServ = new ClientSDKSoapClient("ClientSDKSoap"))
{
WebServ.ClientLogout(Information);
}
}
}
Additional Information
I want the web service to record if the Connection Class is destroyed for any given reason.
When the client is connecting, it works perfectly. The Web Service records every method called from it. If I call ClientLogout explicitly, it will work.
I am aware I can implement IDisposable; however, this object is not intended to be used within the lifetime of one method. In fact, its intended for use for the entire duration of the program and the failure of this object basically results in the failure of the entire project. (Although I suppose main IS a method...)
I need to release a network connection; however, its not in this program, its in another program and unless ClientLogout is called, it won't be released.
My Research
Microsoft says that you should use the deconstructor for the release of unmanaged resources making an explicit reference to network connections. This ones got my quite stumped.
I think you should implement a Dispose pattern for your Connection class, rather than relying on an obscure deconstructor metaphor. This would be the "canonical" way to do it.
public class Connection : IDisposable // <== Inherit from IDisposable interface
{
public const int Port = 50000;// Can be any range between 49152 and 65536
private SomeType webserv; // Use whatever real type is appropriate here.
private Information information = new Information(); // or whatever
// This is a real constructor.
public Connection()
{
//SetInformation
information.Id = 545;
webServ = new ClientSDKSoapClient("ClientSDKSoap"))
webserv.ContinueConnection.WaitOne();
webServ.ClientLogin(information);
}
// Implement IDisposable interface
public void Dispose()
{
webServ.ClientLogout(information);
}
}
And then use it thusly
using (var connection = new Connection())
{
// Use the connection here.
}
The client will be logged out when you leave the using block.
Microsoft says that you should use the deconstructor for the release of unmanaged resources making an explicit reference to network connections. This ones got my quite stumped.
The docs here are misleading. It really just means you need a finalizer somewhere in your object inheritance chain, to ensure that any unmanaged resources are appropriately cleaned up. But you only need this finalizer once for the entire inheritance tree, at the level where the unmanaged resource is first allocated.
As an example, you do not need a destructor or finalizer if you build a class for a data access layer to wrap the SqlConnection type, because the core SqlConnection type already has one. What you should do, though, is implement IDisposable and write code to ensure prompt disposal, so the finalizer on your SqlConnection will be called sooner, rather than later. But if you were to build a whole new database engine that competes with Sql Server, MySql, Oracle, Access, and the like, and were implementing the ADO.Net provider for this new database engine, then would need to write a finalizer for your connection type, because none exists yet.
In this case, ClientSDKSoap type already has a destructor; you do not need to write another.

Do I have to Dispose the SQLiteCommand objects?

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

What happens if i return before the end of using statement? Will the dispose be called?

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.

Using the using statement in C# [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What is the C# Using block and why should I use it?
I have seen the using statement used in the middle of a codeblock what is the reason for this?
The using syntax can(should) be used as a way of defining a scope for anything that implements IDisposable. The using statement ensures that Dispose is called if an exception occurs.
//the compiler will create a local variable
//which will go out of scope outside this context
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}
Alternatively you could just use:
FileStream fs;
try{
fs = new FileStream();
//do Stuff
}
finally{
if(fs!=null)
fs.Dispose();
}
Extra reading from MSDN
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.
It is often used when opening a connection to a stream or a database.
It behaves like a try { ... } finally { ... } block. After the using block, the IDisposable object that was instantiated in the parenthesis will be closed properly.
using (Stream stream = new Stream(...))
{
}
With this example, the stream is closed properly after the block.
using is try finally syntaxical suger for anything that has an IDisposable.. like a sqlconnection. Its use it make sure something is disposed after its out of the using(){} scope.
using(SqlConnection conn = new SqlConnection(connString))
{
//use connection
}
//shorter than
SqlConnection conn = new SqlConnection(connString)
try
{
//use connection
}
finally
{
conn.Dispose();
}
The using statement ensures an object is properly disposed once it is nolonger required.
It basically saves you writing obj.Dispose(); and gives a visual guide as to the scope and usage of an variable.
See the MSDN page for more info
This form of using has to do with freeing resources. It can only be used in combination with class that implement the IDisposable interface.
example:
using(SqlConnection conn = new SqlConnection(someConnectionString))
{
//Do some database stuff here
}
at the end of the using block conn.Dispose is called, even if an exception was thrown inside the block. In the case of a SwqlConnection object means that the connection is always closed.
A drawback of this construction is that there is now way of knowing what happend.
Hope this helps answer your question?
Whenever your code creates an object that implements IDisposable, your code should do the creation inside a using block, as seen above.
There is one exception to this rule. An error in the design of WCF proxy classes prevents using statements from being useful for proxy classes. Briefly, the Dispose method on a proxy class may throw an exception. The WCF team saw no reason not to permit this.
Unfortunately, not seeing a reason doesn't mean that there is no reason:
try
{
using (var svc = new ServiceReference.ServiceName())
{
throw new Exception("Testing");
}
}
catch (Exception ex)
{
// What exception is caught here?
}
If the implicit Dispose call throws an exception, then the catch block will catch that exception instead of the one thrown within the using block.

Categories

Resources