What is the proper way of closing a tread after running a query against a MySql database from a windows form in C#?
Is a simple open close enough like this?
conn.Open();
//querycode
conn.Close():
Try to use:
using(MySqlConnection conn = new MySqlConnection(connString))
{
conn.Open();
} // conn is automatically closed and disposed at the end of the using block
it is okay the way you are doing it, you can also wrap connection object into using block like this:
using (var con = new MySqlConnection(/*connection string*/))
{
con.Open();
//do stuff
// con.Close(); //don't need this it will be closed automatically*
}
(*see)
No, the code in your question is not good enough. If your query throws an exception you won't Close() it in a timely manner and it will be left hanging until the garbage collector notices it.
You need to enclose the object in a using block as shown by others or at a bare minimum encase it in a try/finally structure.
Classes that use resources that you need to clean up afterwards usually implement the IDisposable interface. This means it provides a function called Dispose() that can be used to free resources.
For disposable objects, you can use the using statement:
using ( SomeDisposableClass c = new SomeDisposableClass() ) {
// ... your code here
} // c.Dispose() automatically called here, freeing up resources
If the class is properly coded, it should free any resources -- be it a database connection, an opened file handle, etc -- in its Dispose() function.
This means that the MySQL probably disconnects from the database in Dispose(), so you probably don't need to explicitly call c.Close() -- but always check the documentation to be sure.
Related
I am the third generation to work on a system within my organization and of course there are differences in programming styles. I was wondering what the correct way of connecting to a database is as there are two different styles being used within the system. So whats the "correct" way?
Method 1:
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("StoredProcedure", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("foo", bar));
}
using (SqlDataReader reader = command.ExecuteReader())
{
//do stuff
}
}
}
catch (Exception ex)
{
//do stuff
}
Method 2:
// Variables
SqlCommand loComm;
SqlConnection loConn = null;
SqlDataReader loDR;
try
{
// Init command
loComm = new SqlCommand("foo");
loComm.CommandType = CommandType.StoredProcedure;
loComm.Parameters.AddWithValue("foo", bar);
// Init conn
loConn = new SqlConnection(String);
loConn.Open();
loComm.Connection = loConn;
// Run command
loDR = loComm.ExecuteReader();
//do stuff
}
catch (Exception ex)
{
//do stuff
}
While both methods work I am not sure which one is the most appropriate to use. Is there a reason to use one over the other? The second method is cleaner and easier to understand to me, but it doesn't automatically run the iDispose() function when it is finished.
Edit: My question is different then the one suggested, because one approach uses the "using" statement while the other doesn't. So my question is directly related to whether or not to utilize the "using" statements when making a database connection.
Thanks, for all the responses.
Method 2 is simply incorrect and should be repaired.
When completed, you will be left with IDisposable instances that have not been disposed. Most likely, this will play havoc with the connection management that goes on behind the scenes with SqlConnection, especially if this code gets thrashed a lot before GC decides to step in.
If an instance is IDisposable, then it needs to be Disposed of, preferably in the smallest scope possible. Using using will ensure that this happens, even if the code malfunctions and exceptions are thrown.
A using statement:
using(var disposableInstance = new SomeDisposableClass())
{
//use your disposable instance
}
is (give or take a few minor details) syntactic sugar for:
var disposableInstance = new SomeDisposableClass();
try
{
//use your disposable instance
}
finally
{
//this will definitely run, even if there are exceptions in the try block
disposableInstance.Dispose();
}
Even if something goes wrong in the try block, you can be assured that the finally block will execute, thereby ensuring that your disposables are disposed, no matter what happens.
In the first example, if there is an exception thrown, the objects wrapped in the using blocks will be properly closed and disposed.
In the second, you will manually need to dispose of your objects.
One other thing worth mentioning is that if you were planning on disposing of your objects only when an exception is thrown, you will have objects that are not disposed of, so you would need to implement a try..catch..finally and dispose the objects within the finally block.
The first is the better option.
The first one will close the connection if an exception is thrown.
The second one won't, so I'd say go with the first choice.
What the using block does is to warranty that the object Dispose method will always be invoked, no matter if an exception is thrown or not.
Dispose is a method used to clean up resources. In the case of a DB connection, the connection is released, which is really important.
So, the correct way in this case is using the using pattern.
The object included between the using parents mus be IDisposable whic means that it has a Dispose method that should be invoked when the object is no longer needed. If you don't invoke dispose, it will be disposde at any indeterminate time, when the garbage collector destroys the object. That's undesirable in case like a DB connection that must be closed as soon as possible.
The equivalen of usin is a try finally, which includes a call to Dispose within the finally block.
Reading here, it says:
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.
That sounds like the correct way is method 1.
I keep finding conflicting results for this question. Let's look at this C# code of running an SQL query:
using (SqlConnection cn = new SqlConnection(strConnectString))
{
cn.Open();
using (SqlCommand cmd = new SqlCommand(strSQL, cn))
{
cmd.ExecuteNonQuery();
}
//Do I need to call?
cn.Close();
}
Do I need to call that last cn.Close()? The reason I'm asking is that in a heavy traffic web app I run out of connections in a pool.
The using keyword as used here:
using (SqlConnection cn = new SqlConnection(strConnectString))
{
// Stuff
}
is short for:
SqlConnection cn = null;
try
{
cn = new SqlConnection(strConnectString);
// Stuff
}
finally
{
if (cn != null) cn.Dispose();
}
cn.Dispose() will be called immediately after cn goes out of scope of the using, which in turn immediately closes the connection (because SqlConnection.Dispose() does just that).
UPDATE
This should not be confused with garbage collection. GC is non-deterministic in .NET, which is exactly why the IDisposable inteface and Dispose Pattern were introduced. IDisposable allows expensive resources to be released in a timely, deterministic manner.
Not necessary to close it if you use using as it calls Displose() internally.
Here's a bit details about using keyword in ADO.NET, might be worth reading.
Leveraging the "using" keyword in C#
A quick search #SO will lead you to this post, where you can find your answers there too.
You dont need to close the connection when you use the Using statement.
Scott hanselman explains it here Why The Using Statement Is Better Than A Sharp Stick In The Eye And A SqlConnection Refactoring Example.
In a heavy traffic web app I run out of connections in a pool.
Make sure you are using the same connection string this way SQL will use Connection Pooling.
is the connection closed immediately, or is it closed when the garbage
collector gets to it
Edit:
The Dispose pattern is used to provide deterministic destruction of resources. Since the .net runtime garbage collector is non-deterministic (which means you can never be sure when the runtime will collect old objects and call their finalizer). Therefore, when you implement the Dispose pattern properly you provide deterministic release of the resources and in cases where the consumer is careless and does not dispose the object, the finalizer will clean up the object.
This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Using the using statment in c#
What is the C# Using block and why should I use it?
Just wondering what this means? I've seen lots of tutorials online that have the syntax:
using (SqlCeCommand cmd2 = new SqlCeCommand("SELECT city FROM cities JOIN states ON states.id=cities.state WHERE states.state='" + read.GetString(0) + "'", con))
{
SqlCeDataReader readCities = cmd2.ExecuteReader();
while (readCities.Read())
{
parent.Nodes.Add(readCities.GetString(0));
}
}
Why is it used? I tried searching Google, but it comes up with the 'using' keyword which is used for including dll's and other files.
The using statement
using(var disposableObject = new object_that_implements_IDisposable()) { ... }
is syntactic sugar for code similar to following:
var disposableObject = new object_that_implements_IDisposable()
try
{
...
}
finally
{
if(disposableObject != null)
{
((IDisposable)your_object).Dispose();
}
}
This is only applicable for classes that implement IDisposable. It is helpful for cleaning up code where you have objects that take, for example, system resources (file handles, database connections, sockets, etc.) that need to be cleaned up after you are done to free the resource for the rest of the system.
In theory, you could leave out the .Dispose() call, but then you would have to wait for the Garbage Collector to free the kept resources. The GC is awesome at knowing when to free objects to reclaim their memory usage, but it has no idea that it needs to free objects to have them give up other system resources. Thus, these critical resources might not be given up until after the GC decides it needs the memory used by the owner. Thus, you definitely want to dispose of your objects when you are done with them (if they are disposable)!
As to why you'd use using over try/finally, it is purely a coder's preference. I prefer using because you can cascade them:
using(var a = new class())
using(var b = new class())
using(var c = new class())
using(var d = new class())
{
...
}
You'd need quite a few more lines of code to do that with try/finally.
using has additional advantages as well. For example, whereas calling x.Dispose directly might throw a NullReferenceException if x is null, using(x) will not.
See also:
Link
Using the using statement in C#
What is the C# Using block and why should I use it?
http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx
The using just instructs the compiler to write code that will call the Dispose method on the variable you're using. Only types that implement 'IDisposable' can be used with using statements.
In your example, cmd2 will be disposed when the code in the {} finishes.
"Defines a scope, outside of which an object or objects will be disposed"
See using statement
using is applied to objects that implement IDisposable. It ensures that, when leaving the using block (whether normally, or via an exception, or whatever), the disposable object's Dispose method is called.
Using statement is defines a scope, that outside of it the object or objects will be disposed.
Using is a cool way of cleaning up resources, it is equivalent to try{}catch{}finally{dispose}. Effective c# has an item on this and I bet you willget 10+ similar answers.
http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660
See http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx
The using statement encapsulates variables inside of it in a scope. When the execution exits the using block, all objects inside of it are disposed from memory. You might see it with DB connections so that when the using block exits the resources allocated to that connection are cleaned up and closed.
The using statement defines a scope in which to use an object which implements the IDisposable interface. The object will be cleaned up once the block has been exited. See:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
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();
}
The Entity Framework context object implements a Dispose() method which "Releases the resources used by the object context". What does it do really? Could it be a bad thing to always put it into a using {} statement? I've seen it being used both with and without the using statement.
I'm specifically going to use the EF context from within a WCF service method, create the context, do some linq and return the answer.
EDIT: Seems that I'm not the only one wondering about this. Another question is what's really happening inside the Dispose() method. Some say it closes connections, and some articles says not. What's the deal?
If you create a context, you must dispose it later. If you should use the using statement depends on the life time of the context.
If you create the context in a method and use it only within this method, you should really use the using statement because it gives you the exception handling without any additional code.
If you use the context for a longer period - that is the life time is not bound by the execution time of a method - you cannot use the using statement and you have to call Dispose() yourself and take care that you always call it.
What does Dispose()do for an object context?
I did not look at the code, but at least I exspect it to close the database connection with its underlying sockets or whatever resources the transport mechanism used.
Per Progamming Entity Framework: "You can either explicitly dispose the ObjectContext or wait for the garbage collector to do the job."
So in short, while the using statement isn't required, it's best practice if you know you're done using the ObjectContext since the resource is freed up immediately instead of waiting for garbage collection.
Since you don't know when the garbage collector disposes an item, it's always good to wrap up objects that implement IDisposable in a using-block if you know when you're done with it.
EF5 and before version
using { ...
// connecction open here.
...
context.Blogs.Add(blog);
context.SaveChanges(); // query etc now opens and immediately closes
...
context.Blogs.Add(blog);
context.SaveChanges(); // query etc now opens and immediately closes
}
EF6 and after version
using {
// connecction open here.
...
context.Blogs.Add(blog);
context.SaveChanges();
// The underlying store connection remains open for the next operation
...
context.Blogs.Add(blog);
context.SaveChanges();
// The underlying store connection is still open
} // The context is disposed – so now the underlying store connection is closed
Reference: http://msdn.microsoft.com/en-us/data/dn456849#open5
Always, if you instantiate a class that implements IDisposable, then you are responsible for calling Dispose on it. In all but one case, this means a using block.
When you dispose, the ObjectContext disposes other owned objects.
Including things like the EntityConnection which wraps the actual database connection, i.e. generally a SqlConnection.
So 'if' the SqlConnection is open it will be closed when you dispose the ObjectContext.
I realy tested this thing for both ADO.net and EF v.6 and watched connections in SQL table
select * from sys.dm_exec_connections
Methods to be tested looked like this:
1) ADO.net with using
using(var Connection = new SqlConnection(conString))
{
using (var command = new SqlCommand(queryString, Connection))
{
Connection.Open();
command.ExecuteNonQueryReader();
throw new Exception() // Connections were closed after unit-test had been
//finished. Expected behaviour
}
}
2) ADO.net withour using
var Connection = new SqlConnection(conString);
using (var command = new SqlCommand(queryString, Connection))
{
Connection.Open();
command.ExecuteNonQueryReader();
throw new Exception() // Connections were NOT closed after unit-test had been finished
finished. I closed them manually via SQL. Expected behaviour
}
1) EF with using.
using (var ctx = new TestDBContext())
{
ctx.Items.Add(item);
ctx.SaveChanges();
throw new Exception() // Connections were closed, as expected.
}
2) EF without using
var ctx = new TestDBContext();
ctx.Items.Add(item);
ctx.SaveChanges();
throw new Exception() // Connections WERE successfully closed, as NOT expected.
I don't know why is it so, but EF automatically closed connections. Also All the patterns of repository and UnitOfWork which use EF don't use using. It's very strange for me, because DBContext is Disposable type, but it's a fact.
Maybe in Microsoft they did something new for handling?
I have noticed (although in only one application) that the explicit disposal was causing thread abort exceptions in mscorlib which are caught before the application code, but at least in my case resulting in a noticeable performance hit. Haven't done any significant research on the issue, but probably something worth consideration if you are doing this. Just watch your DEBUG output to see if you are getting the same result.
If Dispose closes connection to DB it is a bad idea to call it.
For example in ADO.NET connections are in connection pool and never be closed before timeout or application pool stop.