Best Practice-use using ()

Source: Internet
Author: User

When we create an objectcontext instance, we always add it to the using () statement. As follows:

 
Using(VaRContext =NewEfrecipesentities ()){...}

 

If you are not familiar with this mode, it does not matter. This is very simple. Generally, when we create an instance object, we use the new operator and assign values to some of its variables. When a variable is out of its own range and an object is not referenced by other things, the garbage collection mechanism will exercise its responsibilities at a certain time and re-allocate the memory space to the object. This mechanism is good, because in. netProgramWe will create numerous objects, and most of these objects will occupy certain resources. when not in use, we will wait for the garbage collector to reclaim these objects. But the garbage collector is uncertain. It handles these resources according to its own schedule, which is uncontrollable for programmers. The objectcontext object holds resources such as database connections, which should be released immediately after processing, rather than waiting for the garbage collector to process it slowly.
The Using statement has the following advantages:

    • WhenCodeWhen the Execution leaves the using () {} range, the dispose () method in the context is automatically called (because objextcontext implements the idisposable interface ). In objectcontext, the dispose method closes all active database connections and appropriately clears other resources to be released.
    • The dispose () method is called no matter how the Code leaves the using {} range. More importantly, it also contains the Return Statement and exceptions that may be thrown in the code segment. Using () {} ensures that critical resources can be properly accessed

Therefore, the best practice proposed here is: when you want to create an objectcontext instance, encapsulate your code in the using () {} block. You just need to upload a bullet-proof clothing to your code.

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.