Use using and try/finally statements to clear Resources

Source: Internet
Author: User
Tags finally block

To use an unmanaged resource type, you must implement the IDisposable interface's Dispose () method to precisely release system resources .. The rule in the. Net environment allows the release of resource code to be a type of user, rather than a type or system. Therefore, whenever you use a type with the Dispose () method, you have the responsibility to call the Dispose () method to release resources. The best way to ensure that Dispose () is to use the using statement or try/finally block.

All types that contain unmanaged resources should implement the IDisposable interface. In addition, when you forget to properly process these types, they will passively create destructor. If you forget to process these pairs, those non-memory resources will be released later when the Destructor are called accurately. This makes these objects wait for a longer period of time in the memory, so that your application will speed down because the system resources are occupying too much.

Fortunately, the precise release of resources by C # Language designers is a common task. They added a keyword to make it easy. Suppose you have written the following code:

  1. Public void ExecuteCommand (string connString,
  2. String commandString)
  3. {
  4. SqlConnection myConnection = new SqlConnection (connString );
  5. SqlCommand mySqlCommand = new SqlCommand (commandString,
  6. MyConnection );
  7. MyConnection. Open ();
  8. MySqlCommand. ExecuteNonQuery ();
  9. }

Two processable objects in this example are not properly released: SqlConnection and SqlCommand. Both objects are stored in the memory until the Destructor is called. (Both classes are inherited from System. ComponentModel. Component .)

 

The solution to this problem is to call their Dispose after using the command and link:

  1. Public void ExecuteCommand (string connString, string commandString)
  2. {
  3. SqlConnection myConnection = new SqlConnection (connString );
  4. SqlCommand mySqlCommand = new SqlCommand (commandString,
  5. MyConnection );
  6. MyConnection. Open ();
  7. MySqlCommand. ExecuteNonQuery ();
  8. MySqlCommand. Dispose ();
  9. MyConnection. Dispose ();
  10. }

This is good, unless the SQL command throws an exception during execution, your Dispose () call will never succeed. The using statement ensures that the Dispose () method is called. When you allocate objects to the using statement, the C # compiler places these objects in a try/finally block:

  1. Public void ExecuteCommand (string connString,
  2. String commandString)
  3. {
  4. Using (SqlConnection myConnection = new
  5. SqlConnection (connString ))
  6. {
  7. Using (SqlCommand mySqlCommand = new
  8. SqlCommand (commandString,
  9. MyConnection ))
  10. {
  11. MyConnection. Open ();
  12. MySqlCommand. ExecuteNonQuery ();
  13. }
  14. }
  15. }

When you use a processing object in a function, the using statement is the easiest way to ensure that the object is properly processed. When these objects are allocated, they will be put into a try/finally block by the compiler. The followingThe two pieces of code are compiled into the same IL.:

  1. SqlConnection myConnection = null;
  2. // Example Using clause:
  3. Using (myConnection = new SqlConnection (connString ))
  4. {
  5. MyConnection. Open ();
  6. }
  7. // Example Try/Catch block:
  8. Try {
  9. MyConnection = new SqlConnection (connString );
  10. MyConnection. Open ();
  11. }
  12. Finally {
  13. MyConnection. Dispose ();
  14. }

If you place a variable that cannot be processed in the using statement, the C # compiler gives an error, for example:

  1. // Does not compile:
  2. // String is sealed, and does not support IDisposable.
  3. Using (string msg = "This is a message ")
  4. Console. WriteLine (msg );

Using can only be used when compiling, And the types that support the IDispose interface can be used, not any object.:

  1. // Does not compile.
  2. // Object does not support IDisposable.
  3. Using (object obj = Factory. CreateResource ())
  4. Console. WriteLine (obj. ToString ());

If obj implements the IDispose interface, the using statement will generate the resource cleaning code. If it is not, using will degrade to using (null), which is safe, but has no effect. If you are not sure whether an object should be placed in the using statement, it is better to be safer: Suppose you want to do this and put it in the using statement in the previous method.

Here is a simple case: Whenever you use a processing object in a method, put this object in the using statement. Now you can learn more complex applications. In the preceding example, we need to release two objects: links and commands. The preceding example shows that two different using statements are created, one containing a processing object. Each using statement generates a different try/finally block. It is equivalent to writing code like this:

  1. Public void ExecuteCommand (string connString,
  2. String commandString)
  3. {
  4. SqlConnection myConnection = null;
  5. SqlCommand mySqlCommand = null;
  6. Try
  7. {
  8. MyConnection = new SqlConnection (connString );
  9. Try
  10. {
  11. MySqlCommand = new SqlCommand (commandString,
  12. & Nbs

Related Article

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.