Use the using keyword to automatically clear object Resources

Source: Internet
Author: User

ApplicationProgramI like to use resources on my computer, rather than considering whether the resources they use are database connections or data in the memory as a stack or array.

 

You can use these resources when necessary, but release them as quickly as possible .. Net Architecture implements this function by using try/catch/Finally, but many developers find it very troublesome to input these statements repeatedly. There are also some other ways to solve the troubles caused by this tedious work, but it is only applicable to certain conditions.

 

Different using keywords

 

If you use C # for development, you will know to use keywords, which can make your program more simple to access these resources. For example, if you need to declare a text box control for the network, you need to enter the following statement:

System. Web. UI. webcontrols. textbox txtname;

On the other hand, ifCodeYou can specify the type at the top, without entering the complete path. The Marked type status can be as follows:

Using system. Web. UI. webcontrols;

If the annotation type uses the preceding statement, you can use the following statement to replace the preceding statement (system. Web. UI. webcontrols. textbox txtname:

Textbox txtname;

Use keywords in C. The preceding statement indicates that the Code uses an object. At the end of the Code, the object resource should be released. The following code provides a better example:

Using (testobject =   New Testobject ()){
// Objects used

}

//Call the release object Method

When processing objects, the above Code is better than try/Catch/FinallyIt is much easier:

Try{

Testobject= NewTestobject ();

//Objects used

}Catch(Exception e ){

//Exception Handling

}Finally{

Testobject. Dispose ();

}

There is a warning in this statement that the object must implement the idisposable interface. Through the implementation interface, you can allocate the resources required for this type of instance.

 

Idisposable

 

The idisposable interface defines a method-a release method-to release resources that have been allocated and are not in use. If you do not want the code to automatically call a method that does not exist, this method is very useful. If you use a keyword for an object and the idisposable interface is not implemented yet, the compiler will return an error message. The following program uses the code to implement idisposable:

 

Public   Class Testobject: idisposable {
Public Testobject (){

//Build code

}

Public VoidDispose (){

//Clear managed resources

Component. Dispose ();

//You also need to know the unmanaged Resources

//The following line is used to clear objects from the queue to prevent further execution.

GC. suppressfinalize (This);

}

}

 

The above statements are useful when you develop your own classes, but many classes already have the above functions. A good example is to connect to the database for running.

 

Example

 

Data is the source of enterprise vitality, and almost all applications are connected to the back-end data. Using using statements to process database objects can provide an opportunity to save key values (reducing the overhead of try/catch/finally ). In addition, I use the Microsoft Data Access Application Block (daab) to further simplify the code. The following excerpt shows how to use the using function for database connections:

 

Using (Sqlconnection Conn =   New Sqlconnection (Global. cvoneconnection)
Conn. open ();

Using(Sqltransaction Trans=Conn. begintransaction ()){

Try{

Sqlhelper. executenonquery (trans, commandtype. storedprocedure,"Sp_name");

Trans. Commit ();

}Catch(Exception ex ){

Trans. rollback ();

ThrowEx;

}}}

 

The Code uses a database transaction to pass a command to a SQL database server (through a saved program ). If no exception occurs, the transaction will be accepted. Note that the try/catch language is still in use in the using function, because catch is indispensable for processing rollback commands. At the same time, because the using function can clear objects in the database connection, the finally function is no longer used. Using the Using Keyword and daab can significantly reduce the number of lines written in the code.

 

VB. NET developer

 

When some people praise the advantages of C #, VB. NET developers often get annoyed, but I am writing this articleArticleIn VB. NET, there is no using function. I have read various reports that the next version of VB. NET will contain the Using Keyword. We will wait and see. I hope that the using keyword will be included in VB. NET, because it does save a lot of time in some cases.

 

Always clear your junk

 

Recently, I worked with a client. He experienced a long wait time in ASP. NET because ASP. NET relies too much on SQL servers. Simply observe the programs opened on the database server and you will find that ASP. NET Applications opened database connections but did not close them. Closing connections and releasing Related Object resources at the right time can greatly improve program performance. The Using Keyword can also alleviate this situation, but VB. NET does not include this function.

Although. the net architecture provides automatic fragment, and can discover memory problems encountered by many old c ++ developers, however, after you use all kinds of resources within the framework, you still need to clear the resources you do not need.

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.