1. Any time you are using a type with a Dispose () method, it is your responsibility to call the Dispose () method to free up resources.
The best way to ensure that Dispose () is called is to use a using statement or a try/finally block
public void ExecuteCommand (string connstring, String commandstring) { using (SqlConnection myconnection = new Sqlco Nnection (connstring)) {using (SqlCommand Mysqlcommand = new SqlCommand ( CommandString, MyConnection)) { C4/>myconnection.open (); Mysqlcommand.executenonquery (); } } }
Translators believe that the above structural problem is the inability to catch exceptions. The author and translator are the same.
SqlConnection myconnection = null; SqlCommand mysqlcommand = null;
myconnection = new SqlConnection (connstring); Mysqlcommand = new SqlCommand (CommandString, MyConnection); Myconnection.open (); Mysqlcommand.executenonquery ();
Catch
{} finally { if (mysqlcommand! = NULL)///Note here it is important to determine whether the object is null, some of the objects that encapsulate COM, and sometimes the release is implicit, an exception occurs when you release some empty objects again mysqlcommand.dispose (); if (myconnection! = null) myconnection.dispose ();} }
SqlConnection it also has close (), the Dispose method frees up more resources, and it tells the GC that the object no longer needs to be refactored
2. Types that use or contain unmanaged resources must implement the Dispose () method of the IDisposable interface to precisely release system resources.
effectivec#15--use using and try/finally for resource cleanup