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
Related
I've been running into some problems concerning a SqlTransaction I'm using in my code. During my Googling I see many people using a using statement with a SqlTransaction.
What is the benefit and/or difference of using this type of statement with a SqlTransaction?
using (SqlConnection cn = new SqlConnection())
{
using (SqlTransaction tr = cn.BeginTransaction())
{
//some code
tr.Commit();
}
}
Currently my code looks like this:
SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"]);
cn.Open();
SqlTransaction tr = cn.BeginTransaction();
try
{
//some code
tr.Commit();
cn.Close();
}
catch(Exception ex)
{
tr.Rollback();
cn.Close();
throw ex;
}
What is the advantage of one way over the other?
A using statement should be used every time you create an instance of a class that implements IDisposable within the scope of a block. It ensures that the Dispose() method will be called on that instance, whether or not an exception is thrown.
In particular, your code only catches managed exceptions, then destroys the stack frame by throwing a new exception instead of rethrowing the existing one.
The correct way to do it is:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"])) {
cn.Open();
using (SqlTransaction tr = cn.BeginTransaction()) {
//some code
tr.Commit();
}
}
Note that if your class has instance members of types that implement IDisposable, then your class must implement IDisposable itself, and dispose of those members during its own Dispose() call.
The reason for this is that the SqlTransaction object will roll back in its Dispose() method if it was not explicitly committed (e.g. if an exception is thrown). In other words, it has the same effect as your code, just a little bit cleaner.
Essentially the using does the same thing that you are doing, except int a finally block instead of catching all exceptions:
using (SqlConnection cn = new SqlConnection())
{
using (SqlTransaction tr = cn.BeginTransaction())
{
//some code
tr.Commit();
}
}
is the same as, just much less code :)
{
SqlConnection cn = null;
try
{
cn = new SqlConnection();
{
SqlTransaction tr = null;
try
{
tr = cn.BeginTransaction())
//some code
tr.Commit();
}
finally
{
if(tr != null && tr is IDisposable)
{
tr.Dispose();
}
}
}
}
finally
{
if(cn != null && cn is IDisposable)
{
cn.Dispose();
}
}
}
In the end, using is just a shortcut for a pattern. But it's a very useful and helpful shortcut, because it ensures you implement the pattern correctly and means you can do it with less code.
In this case, you haven't implemented the pattern correctly. What happens in your code if the call to tr.RollBack() also throws an exception?
The using statement is closing and disposing your connection and transaction for you. It's the equivalent of having a finally block on your try/catch that does the dispose.
You could also condense the using blocks down a bit like this...
using (SqlConnection cn = new SqlConnection())
using (SqlTransaction tr = cn.BeginTransaction())
{
//some code
tr.Commit();
}
which would be roughly the same as:
SqlConnection cn = null;
SqlTransaction tr = null;
try
{
cn = new SqlConnection());
tr = cn.BeginTransaction());
//some code
tr.Commit();
}
finally
{
if (cn != null)
cn.Dispose();
if (tr != null)
tr.Dispose();
}
If you don't use a using() block, you'll have to explicitly call the .Dispose() method of the SqlConnection and SqlTransaction objects. If you fail to do that, then unmanaged resources will not be released and could cause memory leaks or other problems.
Using using gurantees that your connection object will be disposed after the code returns. Dispose is useful to release unmanages resources, As a good practice, if an object implements IDisposable, dispose method always should be called
In addition to all that, it prettifies your code. Doesn't the 7 lines of code look better than the 14 lines? I breath a sign of relief every time I see a using block. It's like that little squirt of mist that comes out of that glad smelly thing. Mmm, I'm a pretty block of efficient code. Look at how well I manage memory and how pleasing I am to the eye.
I frequently use the following code (or alike) to dispose of objects:
SqlCommand vCmd = null;
try
{
// CODE
}
catch(Exception ex) { /* EXCEPTION HANDLE */ }
finally
{
if (vCmd != null)
{
vCmd.Dispose();
vCmd = null;
}
}
Is this the best way to release objects and dispose of objects?
I'm using the VS analytics and give me a warning about redundancies. But I always do it this way...
The best way in terms of readability is using the using statement:
using(SqlCommand vCmd = new SqlCommand("...", connection)
{
try
{
// CODE
}
catch(Exception ex)
{
// EXCEPTION HANDLE
}
}
It disposes objects even in case of error, so similar to a finally. You should use it always when an object implements IDisposable which indicates that it uses unmanaged resources.
Further reading:
Cleaning Up Unmanaged Resources
there is no need to set objects to null.
Here is an example from MSDN:
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
Note the use of "using" for the connection.
Back in the Olden Days of COM/ActiveX, you needed to set your objects to "Nothing".
In managed code, this is no longer necessary.
You should neither call "Dispose()", nor set your sqlCommand to "null".
Just stop using it - and trust the .Net garbage collector to do the rest.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If I return a value inside a using block in a method, does the using dispose of the object before the return?
I have this code (simplyfied):
bool method1()
{
using (OleDbConnection con = new OleDbConnection(connString))
{
bool b = false;
try
{
con.Open();
b = true;
}
catch (Exception)
{
b = false;
}
finally
{
con.Close();
return b;
}
}
}
I return before the closing curly bracket of the "using" statment. Does my object "con" gets Disposed anyway? Is is better to use the following code?:
bool method1()
{
bool b = false;
using (OleDbConnection con = new OleDbConnection(connString))
{
try
{
con.Open();
b = true;
}
catch (Exception)
{
b = false;
}
finally
{
con.Close();
}
}
return b;
}
The whole point of the using statement is that it automates the disposal of an object, even if an unhandled exception is thrown from within the using block.
Therefore, once your code exits the using block, whether it's returning or otherwise, then the object being 'used' us disposed.
It is completely safe to return during a using statement due to the .NET magic of automatically handling disposal of objects. The whole idea is that you don't have to think about how you exit out of the using block, you just know that when you leave it the object will be disposed correctly. Because of such, your example could be simplified to this:
bool method1()
{
using (OleDbConnection con = new OleDbConnection(connString))
{
try
{
con.Open();
return true;
}
catch (Exception)
{
return false;
}
}
}
con.Close() can be removed as well as it is automatically called by the disposal.
Look at this if you want to see what happens under the hood.
there is no difference between two code sections; con object will be disposed in both examples.
In the first example you set a temporary variable and return that.
About the return in the finally: What happens after compilation is that you branch to the end of the method and then return a temporary variable.
E.g. the results is exactly the same. Just for clarity I would personally prefer the first one, because it resembles what happens more exactly.
using expands into somewhat more complex with additional if statement like
OleDbConnection con = new OleDbConnection(connString)
try
{
con.Open();
}
finally
{
// Check for a null resource.
if (con != null)
// Call the object's Dispose method.
((IDisposable)con).Dispose();
}
So in your example you might get NullReferenceException in finally block.
So if you want to return the status of operation and Dispose and object, I suggest to use this code snippet
using(OleDbConnection con = new OleDbConnection(connString))
{
try
{
con.Open();
return true;
}catch(OleDbException ex)
{
//log error
return false;
}
}
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.
Suppose that I have the following code:
private void UpdateDB(QuoteDataSet dataSet, Strint tableName)
{
using(SQLiteConnection conn = new SQLiteConnection(_connectionString))
{
conn.Open();
using (SQLiteTransaction transaction = conn.BeginTransaction())
{
using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM " + tableName, conn))
{
using (SQLiteDataAdapter sqliteAdapter = new SQLiteDataAdapter())
{
sqliteAdapter.Update(dataSet, tableName);
}
}
transaction.Commit();
}
}
}
The C# documentation states that with a using statement the object within the scope will be disposed and I've seen several places where it's suggested that we don't need to use try/finally clause.
I usually surround my connections with a try/finally, and I always close the connection in the finally clause. Given the above code, is it reasonable to assume that the connection will be closed if there is an exception?
You are correct; the using statement compiles to a try / finally block.
The compiler transforms using(resource) statement; into the following code:
{
ResourceType resource = expression;
try {
statement;
}
finally {
if (resource != null) ((IDisposable)resource).Dispose();
}
}
(The cast to IDisposable is in case ResourceType implements IDisposable explicitly.
Yes, you either need to use a try/finally or a using statement. You don't need both.
A using statement is almost the same as a try/finally except that in C# 3 you can't reassign to the variable inside the using block.
using (IDisposable d = foo())
{
d = null; // Error: Cannot assign to 'd' because it is a 'using variable'
}
Previously you could reassign but the original object would still be disposed, not the newly assigned object and you would also get this compile warning:
Possibly incorrect assignment to local 'd' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.
Yes, the using statement is pretty much just shorthand for a try ... finally block.
For example, this code...
using (MyDisposableType foo = new MyDisposableType())
{
foo.DoSomething();
}
...would equate to the following...
{
MyDisposableType foo = new MyDisposableType();
try
{
foo.DoSomething();
}
finally
{
if (foo != null)
((IDisposable)foo).Dispose();
}
}
You can assume that the connection will be closed if you get an exception.
Using() ensures that the item instantiated within the parameters will be disposed of regardless of that happens within the associated code block. This includes closing the database connection assuming that SQLiteConnection handles its disposal correctly.