using statements are always necessary? Or It can be avoid? [duplicate] - c#

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

Related

Are 'using' blocks thread safe?

If I am calling some data access methods from multiple threads, do I need to lock the code around the DB calls to ensure consistency, or are the using statements below atomic?
public static DataRow GetData(Int32 id)
{
using (SqlConnection con = new SqlConnection(connectionString);)
{
con.Open();
SqlCommand cmd = ...
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(...)
cmd.Parameters.Add(...)
DataTable dt = new DataTable();
return new SqlDataAdapter(cmd).FillWithRetry(dt, sqlGetEmail.CommandText);
}
}
I don't think one thread can affect the connection object defined and 'in use' from another.
Using statements have nothing to do with thread-safety (or lack of).
They merely ensure that Dispose method of the used object is called when the block ends; but are otherwise equivalent to a manual try..finally Dispose.
In this particular case: since a new connection is opened on each thread then it is 'thread safe'. It still might not be atomic wrt. the database or other shared state.
I don't think one thread can affect the connection object defined and 'in use' from another.
So I suppose you are worrying your connection's concurrent access. The using statement is not a lock. If you want to use exclusively a connection or any other instance you should use:
lock(myConnection)
{
// your code
}
What the using keyword is for that's described here
However I think there is other misunderstandings here:. In your example your connection is a local variable what is instantiated as many times as the control flow enters to your GetData method (even in different threads). So even the control flow reenters multiple times (and in different threads) to the method, no shared connection instance will be used, each entering to the method creates its own instance.
It would be different the case if the connection instance would be a parameter. Then you should worry about concurrency, and use a lock.
Conclusion: In your sample you do NOT need to worry about your connection instance concurrent access, and you do not need to use any locking semantics.
Interestingly in your sample using of using is indeed correct, because Connection is IDisposable, so you should apply a deterministic dispose guard around its usage with try/finally or better with its shortcut: the using keyword.

Will doing this keep the mysql connection open?

Basically i store a certain dataset in asp.net cache. What i'm wondering is if doing it this way will keep the mysql connection open? even though i'm using the "using" statement?
String cacheName="MY_QUERY_QACHE";
IEnumerable<DataRow> datarows = (IEnumerable<DataRow>)HttpRuntime.Cache[cacheName];
if(datarows==null){
using (MySqlConnection conn = new MySqlConnection("MY CONNECTION STRING")){
conn.Open();
String strSQL="SELECT * FROM my_table etc... etc....";
MySqlCommand cmd = new MySqlCommand(strSQL, conn);
MySqlDataAdapter da = new MySqlDataAdapter();
DataSet ds = new DataSet();
cmd.Prepare();
da.SelectCommand = cmd;
da.Fill(ds);
datarows = ds.Tables[0].AsEnumerable();
conn.Close();
}
HttpRuntime.Cache.Add(cacheName,
datarows,
null,
DateTime.Now.AddDays(1),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal,
null
);
}
The Using Statement will adhere to the following:
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. 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)
The usage of that statement should ensure that the connection is closed no matter what happens. As noted the connection will still be closed even with an Exception. The reason is your connection does not exist out of this:
// Connection Doesn't Exists
using(SqlConnection connection = new SqlConnection())
{
// Connection Exists
}
// Connection Doesn't Exists.
As you can see by the above code, anything that falls out of those brackets becomes out-of-scope which will initiate the IDisposable interface with the method Dispose to remove the resource. If you didn't utilize the using then you would leave it open and become responsible for handling it.
Hopefully that answers your question. There is great detail on Microsoft's Developer Network on this as well.
The point of "using" is to invoke disposal (cleanup) when execution leaves the using scope. The connection object inherits from IDisposable so that it can do cleanup when required (and not wait for garbage collection), and for a connection, cleanup means terminating the database connection.
So, yes, outside the using scope, there will be no connection to the database.
Your MySqlConnection object doesn't exist outside the scope of the using block. Within a using block, Dispose is called on the object which implements IDisposable on exit. Objects which implement IDisposable will not automatically dispose if not declared in a using block. In this case, Dispose will need to be called manually to clean up resources.

When do we need to call Dispose() in dot net c#?

Do I need to dispose a sqldatareader after it is created?
SqlDataReader reader;
---
---
---
reader.Close();
reader.Dispose();
Rule of thumb: if a class implements IDisposable you should always call the Dispose method as soon as you have finished using this resource. Even better wrap it in a using statement to ensure that the Dispose method will be called even if an exception is thrown:
using (var reader = conn.ExecuteReader())
{
...
}
Object which are Disposable can be best used (if possible) in a using block. At the end of the using block, the object is automatically disposed.
Because of memory management it is always advised do dispose your objects if you don't need them anymore.
Here's some stuff to read from the MSDN.
It is recommended to use the using pattern when dealing with anything that implements IDisposable
using ()
{
// use it here
}
This will look after the try..catch..finally construct and calling Dispose.
EDIT I had previously said that I thought Close and Dispose did the same thing for readers (stream, file, sqldatareader etc.) but it appears this is not true looking at the documentation on SQLDataReader so my assumption was wrong.
There is a simple guideline: if you have finished with an object whose type implements IDisposable then call Dispose() on it; you should use a using block to do this.

Is closing/disposing an SqlDataReader needed if you are already closing the SqlConnection?

I noticed This question, but my question is a bit more specific.
Is there any advantage to using
using (SqlConnection conn = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand())
{
// dostuff
}
}
instead of
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand command = new SqlCommand();
// dostuff
}
Obviously it does matter if you plan to run more than one command with the same connection, since closing an SqlDataReader is more efficient than closing and reopening a connection (calling conn.Close();conn.Open(); will also free up the connection).
I see many people insist that failure to close the SqlDataReader means leaving open connection resources around, but doesn't that only apply if you don't close the connection?
In my opinion, there are two rules to follow here:
Classes that implement IDisposable should be wrapped in a using block.
You should not rely on a class's implementation of IDisposable to ignore rule 1.
That is, even if you know that disposing the connection object took care of disposing its associated command object, you should not rely on this behavior.
By the way, it's possible to nest using blocks in a cleaner fashion:
using (SqlConnection conn = new SqlConnection(conStr))
using (SqlCommand command = new SqlCommand())
{
// dostuff
}
and I would use
SqlCommand command = conn.CreateCommand();
instead of creating a new SqlCommand and then associating it with the connection.
Technically it's not needed; closing a SqlConnection should destroy any resources that the SqlDataReader is using. The reverse is also true; you don't need to Dispose the SqlConnection if you dispose a SqlDataReader that was created with CommandBehavior.CloseConnection.
Practically speaking, though, when a class implements IDisposable, you should Dispose it when you're finished with it. The implementation details of framework classes are subject to change at any time, and unless the documentation specifically outlines circumstances under which it is not necessary to Dispose the instance, there is always a possibility that some future change/update will result in your code having a resource leak.
It's really no extra effort - so just wrap it in a using block.
It may not be necessary in a lot of cases, but it's best practice for a reason. There's no reason to let resources persist beyond the point where they are no longer useful. The using construct helps ensure this.
Isn't it just a matter of you freeing the resource now vs. garbage collection freeing it later?
There's a difference. If you create 2 of those readers without opening/closing the connection, but don't dispose of the first one before using the second, you'll get a conflict saying the connection is already associated to an open reader.

Overhead of creating new SqlConnection in c#

A while back I wrote an ORM layer for my .net app where all database rows are represented by a subclass of DatabaseRecord. There are a number of methods like Load(), Save() etc. In my initial implementation I created a connection to the DB in the constructor of DatabaseRecord e.g.
connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString
);
I then call Open() and Close() on that SqlConnection at the beginning and end of my methods which access the database. This seemed to me (as someone who was familiar with programming but new to c# and .net) to be the most efficient way to do things - have one connection and open/ close it where necessary within the class.
I've just been doing some reading though and it appears that this pattern is recommended in a number of places:
using (var connection = new SqlConnection(...)) {
connection.Open();
// Stuff with the connection
connection.Close();
}
I can see why it's desirable - the connection is automatically Dispose()d even if the stuff you do in the middle causes an uncaught exception. I was just wondering what the overhead is for calling new SqlConnection() potentially many times like this.
Connection Pooling is on so I imagine the overhead is minimal and the second approach should be best practice but I just wanted to make sure my assumptions are right.
Yes, it is best practice. The using makes your call to Close() exception-safe.
And the overhead of creating a (any) object is indeed minimal, and smallest for short-lived objects (that stay in GC generation 0).
Note that you don't have to call Close() at the end of the using-block anymore, it is automatically done for you (Dispose==Close).
This is partially a matter of taste. As long as you employ connection pooling the overhead of creating a new (recycling a pooled connection) will be minimal, so generally the recommended pattern is to create new connection objects as needed.
If you run several commands immediately after each other then I see no reason to create new connections for each of them, but you should avoid holding on to open connections for a long time.
Also, you should note that the Dispose method will close the connection for you. So there is no need to call both Close and Dispose. Since the using clause will call dispose when it ends there is normally no need to call Close.
If you're unsure about the cost of opening/closing connection, have the SqlConnection a member variable of your class, but make the class IDisposable and dispose of the SqlConnection when the class is disposed

Categories

Resources