Does placing a SqlCommand.Connection in a using block close the connection in the same way as placing the SqlConnection in it's own using block? (Is #1 = #2)
Example 1
using (var cmd = GetCommandWithConnectionSetInternally(connString))
{
using (cmd.Connection)
{
}
}
Example 2
using(var conn = new SqlConnection(connString))
{
using(var cmd = new SqlCommand(cmdText, conn))
{
}
}
So, does the connection in Example 1 get closed as it would in Example 2 upon exiting the "using" block?
I can't see it working any other way since using is just a short form of try {} finally {} with a Dispose call in the finally block. Since the resource object being used is cmd.Connection, it should get disposed.
Related
SqlDataReader rdr = null;
con = new SqlConnection(objUtilityDAL.ConnectionString);
using (SqlCommand cmd = con.CreateCommand())
{
try
{
if (con.State != ConnectionState.Open)
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(Parameter);
cmd.CommandText = _query;
rdr = cmd.ExecuteReader();
}
catch (Exception ex)
{
throw ex;
}
}
In this above code, sqlconnection is opened inside the managed code. Hence, will the connection object be disposed automatically upon ending the scope of USING?
You have to care about the disposal of SqlConnection, since it's a disposable object. You can try this:
using(var sqlConnection = new SqlConnection(objUtilityDAL.ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
// the rest of your code - just replace con with sqlConnection
}
}
I suggest you replace the con with a local variable - if there isn't already (it does not evident from the code you have posted). There is no need for using a class field for this purpose. Just create a local variable, it would be far more clear to track it.
You should Dispose every temporary IDisposable instance you create manually, i.e. wrap them into using:
// Connecton is IDisposable; we create it
// 1. manually - new ...
// 2. for temporary usage (just for the query)
using (SqlConnection con = new SqlConnection(objUtilityDAL.ConnectionString)) {
// Check is redundant here: new instance will be closed
con.Open();
// Command is IDisposable
using (SqlCommand cmd = con.CreateCommand()) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(Parameter);
cmd.CommandText = _query;
// Finally, Reader - yes - is IDisposable
using (SqlDataReader rdr = cmd.ExecuteReader()) {
// while (rdr.Read()) {...}
}
}
}
Please, notice that
try {
...
}
catch (Exception ex) {
throw ex;
}
is at least redundant (it does nothing but rethrow the exception, while loosing stack trace) and that's why can be dropped out
In general:
In the .Net framework, nothing gets disposed automatically. Otherwise we wouldn't need the IDisposable interface. The garbage collector can only handle managed resources, so every unmanaged resource must be handled in code in the dispose method.
So as a rule, every instance of every class that is implementing the IDisposable must be disposed either explicitly by calling it's Dispose method or implicitly with the using statement.
As best practice, you should strive to use anything that implements the IDisposable interface as a local variable inside a using statment:
using(var whatever = new SomeIDisposableImplementation())
{
// use the whatever variable here
}
The using statement is syntactic sugar. the compiler translates it to something like this:
var whatever = new SomeIDisposableImplementation();
try
{
// use the whatever variable here
}
finally
{
((IDisposable)whatever).Dispose();
}
Since the finally block as guaranteed to run regardless of whatever happens in the try block, your IDisposable instance is guaranteed to be properly disposed.
With SqlConnection specifically, in order to return the connection object back to the connection pool, you must dispose it when done (the Dispose method will also close the connection, so you don't need to explicitly close it) - So the correct use of SqlConnection is always as a local variable inside the using statement:
using(var con = new SqlConnection(connectionString))
{
// do stuff with con here
}
This question already has answers here:
What is the C# Using block and why should I use it? [duplicate]
(9 answers)
Closed 5 years ago.
I wonder that what is the difference between ;
using (var con = new OracleConnection(oradb))
{
con.Open();
// Do sth.
con.Dispose();
con.Close();
}
from this;
oradb = ConString;
OracleConnection con = new OracleConnection(oradb))
con.Open();
// Do Sth.
con.Dispose();
con.Close();
Both of them works for me, However didn't understand the basic behind of this.
Which one should i use ?
If we look at the decompiled code:
using System;
public class C {
public void M() {
using(var conn = new Connection()){
}
}
}
is turned into:
public class C
{
public void M()
{
Connection connection = new Connection();
try
{
}
finally
{
if (connection != null)
{
((IDisposable)connection).Dispose();
}
}
}
}
Unlike the code without a using block, the connection will be disposed even if the exception is thrown.
A bit more reading about the using could be found here (C# Reference doc)
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.
Using ensures that the connection is always disposed. If you dispose it manually it can happen that part of the code is never executed at all.
With using, disposing of connection is handled automaticaly :
using (var con = new OracleConnection(oradb))
{
con.Open();
// Do sth.
con.Close();
} // ok
using with dispose your connection object automatically. you dont have to do it manually.
using(var con = new OracleConnection(oradb))
{
con.Open();
}
is equal to (some what similar , you can use ILDSAM on your code and check)
OracleConnectioncon = null;
try
{
con = new OracleConnection(oradb);
con.Open();
}
finally
{
con.Disponse();
}
you can clear you concept by reading : Dispose Pattern
This question already has answers here:
try/catch + using, right syntax
(9 answers)
Closed 8 years ago.
The following 2 sets of codes produce same results, but I'm wondering which of these is the correct way of wrapping with the try...catch block. What's the difference between the 2 of them?
Edited: Which of this will properly capture the error, and also to make sure the connection will be closed even if there is an exception.
1
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("Drop Table sometable", conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
catch
{
//
}
2
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand("Drop Table sometable", conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch
{
//
}
}
The difference is that in the #2 SqlConnection conn object will be disposed after the catch block will be finished. In #1 your connection will be disposed and than you will end up in the catch block.
Both are fine, depended on if you want to catch an error when opening the connection, and then of course you need to close the connection when you are done with it. usually closing earlier is better.
the difference is:
if you use code 2, and your connString you use in your using statement is invalid, it will throw an exception, because it is not in the try catch block.
in code 1, it will just catch that exception. but you will not be able to use your SqlConnection in the catch block
I thik that you are aware of exception handling.
We write all of our codes inside the catch block that can arise suspicious/unknown behavior to our applications. In that case the catch block handles the suspicious behavior of our application.
In context to your above two block of codes ....
For the first one- any exception caused by any one statement of your codes will be handled by catch block.
But for second one- exception caused by "using (SqlConnection conn = new SqlConnection(connString))" statement cannot be handled by your catch block, because it is outside of the try block. To test this just place some false connection string in sqlconnection.
Hope this will gives you better understanding for your scenario.
The using statement is a syntactic shortcut to represent a try/catch/finally. You could right your code as below, and would have the same effect as your examples above.
SqlConnection conn
try
{
conn = new SqlConnection(connString)
SqlCommand cmd = new SqlCommand("Drop Table sometable", conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch
{
//
}
finally
{
if(conn != null)
{
conn.Dispose()
}
}
I am working on application in which i need to access database. Use of using statement is good because "using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens. So i am little bit confused where to use "using" and where to not.
public int route(Route r)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using(SqlCommand com = new SqlCommand("",con))
{
using (SqlDataReader sdr = com.ExecuteReader())
{
}
}
}
}
catch (Exception e)
{
}
}
Any time an object you create implements IDisposable, disposing of it (with or without the using syntactic sugar) is a good idea.
The benefit of the using block syntactic sugar (over manual .Dispose() calls) is that Dispose() will still be called even if there is an exception and flow leaves the using block.
Also, note that you can stack up the usings, without nested indentation:
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader()) // Still need to open connection ...
{
...
As an aside, a further benefit of using is that if the IDisposable variable is declared within the using, it that the variable is readonly and cannot be reassigned within the block, e.g.:
using (SqlDataReader sdr = com.ExecuteReader())
{
sdr = new SqlDataReader() // Error
You can simplify it like this:
using (SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader())
{
...
}
Using statements are translated to try/finally blocks.Therefore your object will be Disposed even if there is an exception thrown.So if you have a Disposable object and you want to ensure that it will be Disposed after it's used, you can use using statements.Remember it's kind a syntactic sugar for this:
SqlCommand cmd;
try
{
cmd = new SqlCommand();
...
}
finally
{
((IDisposable)cmd).Dispose();
}
This looks okay as far as using blocks are concerned.
However, you should NOT use a try/catch block here, unless you intend on actually doing something with the exception. Otherwise you are just hiding possible errors away, which is dead wrong.
I'm not sure if my question is clear so here's a code sample:
public static bool isRecordExist(int ID)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
int flag = int.Parse(command.ExecuteScalar);
if (flag)
return false;
else
return true;
}
}
}
So, now I understand that I don't need to close or dismiss any Sql objects when I have the 'using' keyword, because it does that automatically as soon as you get our of it's brackets but now the we reach to the 'return' part. will it dismiss and close the objects properly or do I need to save this value and make my check and 'return' outside the 'using' code ?
Yes it closes automatically. Exiting a using block calls .Dispose() on the object in question which for a SqlConnection will close the connection and any open resources.
Does End Using close an open SQL Connection
Yes, the connection will be closed.
Note that this can cause problems. Say, for example, that you want to return a DataReader from the function. As soon as you return the datareader, the connection that your reader depends on is closed by the using block and you can't read any records. In those situations, I use either a delegate or an iterator block to get around the problem, depending on what I'm doing.
Yes, the object will be disposed properly. If you take a look at the IL generated from the method, you will see a try/finally block in the appropriate spots of your using { ... } statements. Exiting the method from any part inside of a using { ... } block will always follow the try/finally dispose pattern.
I also would recommend stacking your using statements like this:
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(commandText, connection))
{
//some work
}
It generally makes the code more readable, especially if you are using 4 or 5 of them.
Yes, because it is syntactic sugar for try/finally without the catch.
So when you do this:
using (SqlConnection connection = new SqlConnection ...) {
code code code then return;}
You get (approximately) this behind the scenes:
SqlConnection connection;
connection = null;
try
{
connection = new SqlConnection ...;
code code code then return;
}
finally
{
if (connection != null) connection.dispose();
}
And by the definition of finally, it is always called, no matter how you break out of the try block (usually you think 'exception' but also including return).