157 suggestions for writing high-quality code to improve C # programs-Recommendation 52: release resources in a timely manner,

Source: Internet
Author: User

157 suggestions for writing high-quality code to improve C # programs-Recommendation 52: release resources in a timely manner,

Suggestion 52: release resources in time

The garbage collection mechanism automatically recycles resources implicitly (the Garbage Collector automatically calls the terminator). Why should we release resources?

private void buttonOpen_Click(object sender,EventArgs e){   FileStream fileStream = new FileStream(@"c:\test.txt",FileMode.Open);           }private void buttonGC_Click(object sender,EventArgs e){   System.GC.Collect();   }

This is an example of a WinForm program. In this example, click a button to open a file, click another button to recycle the garbage that says "Generation" (the concept of generation will be detailed below. If you click the open file button twice in a row, the system reports an error:

IOException: the file "c: \ test.txt" is being used by another process. Therefore, this process cannot access this file.

If you click the open file button and then click the Clear button, the operation is normal.

 

Now let's analyze: in the method of opening a file, after the method is executed, because the local variable fileStream has no reference in the program, so it will be marked as garbage during the next garbage collection. So when will the next garbage collection be performed? When will the Garbage Collector actually start to recycle? Microsoft officially explains that garbage collection will happen when the following conditions are met:

  • The system has low physical memory.
  • The memory used by allocated objects on the managed stack exceeds the acceptable threshold. This means that the acceptable memory usage threshold has exceeded the managed heap. As the process runs, the threshold value is constantly adjusted.
  • Call the GC. Collect method. In almost all cases, you do not have to call this method because the Garbage Collector will continue to run. This method is mainly used for special cases and tests.

 

Releasing resources in a timely manner is a great waste to the system. This waste also interferes with the normal operation of the Program (for example, in this instance, because it occupies file resources, as a result, we cannot use this file resource again ).

If the type inherits the IDisposable interface, although the garbage collection mechanism will automatically release resources for us, this process is extended because it does not complete all cleaning work in a collection. In this example, because fileStream inherits the IDisposable interface, the garbage collector calls the fileStream Terminator for the first garbage collection and waits for the next garbage collection, in this case, the fileStream object may be recycled.

Let's improve this program:

private void buttonOpen_Click(object sender,EventArgs e){    FileStream fileStream = new FileStream(@"c:\test.txt",FileMode.Open);         fileStream.Dispose();      }

However, if the first line of code encounters an exception, it will never be able to execute filsStream. Dispose. Further improvement:

private void buttonOpen_Click(object sender,EventArgs e){    try    {           FileStream fileStream = new FileStream(@"c:\test.txt",FileMode.Open);         }    finally    {        fileStream.Dispose();          }}

Use the syntax sugar "using" keyword to further simplify:

private void buttonOpen_Click(object sender,EventArgs e){    using(FileStream fileStream = new FileStream(@"c:\test.txt",FileMode.Open))    {        }}

 

 

About "Algebra": There are three generations: 0th generation, 1st generation, and 2nd generation.

  • Generation 1: This is the youngest generation, including short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection is the most common occurrence in this generation. The newly allocated objects constitute a new generation of objects and are implicitly recycled by The 0th generation unless they are large objects, in which case they will enter the large object heap in the 2nd generation recycle. Most objects are recycled through garbage collection in the 0th generation and will not be retained to the next generation.
  • Generation 1st: This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.
  • Generation 1: This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is active during a process.

When conditions are met, garbage collection will occur on a specific generation. Recycling a generation means to reclaim the objects in this generation and all the younger generations. 2nd-generation garbage collection is also called complete garbage collection because it recycles all objects on all generations (that is, all objects in the managed heap ).

Survival and Improvement

Unreclaimed objects are also known as survivors and are promoted to the next generation. The surviving objects in the 0th generation of garbage collection will be upgraded to the 1st generation; the surviving objects in the 1st generation of garbage collection will be upgraded to the 2nd generation; the surviving objects in the first generation of garbage collection will remain in the second generation.

When the Garbage Collector detects a high survival rate in a generation, it increases the distribution threshold of the generation, so the next recycle will obtain a very large memory to recycle. CLR balances before the following two priorities: it does not allow the application's working set to obtain too much memory and does not allow garbage collection to take too much time.

Temporary period and temporary period

Because objects in the 0th and 1st generations have a short lifetime, these generations are called the temporary era.

In the current era, it is necessary to allocate memory segments called temporary segments. Each new segment obtained by the garbage collector becomes a new temporary segment and contains the surviving objects in the 0th generation garbage collection. The old temporary segment will become the new 2nd generation segment.

 

For more information, refer to MSDN: the basis of garbage collection.

 

 

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.