effectivec#15--use using and try/finally for resource cleanup

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.