Garbage collection and Resource Manager in C #

Source: Internet
Author: User
Tags finally block readline

Once the variables and objects are created, they are allocated space on memory, and in order to reclaim valuable memory resources, the program should destroy the object or variable at the right time. Here are some ways to summarize:
A, garbage collector--destructor
in C #, you can create an infinite number of references to an object. The number of references to the same object determines the lifetime of the object.

Square mysquare=new MySQUARE ();
Square Anothersquare=mysquare;

A variable (mysquare) disappears, and other variables (anothersquare) may still exist. Therefore, the lifetime of an object cannot be linked to a particular reference variable. This object can only be destroyed after all references to a variable have disappeared.
Why do you use the garbage collector?
1) Not to use the problem:
A) forgetting to destroy the object
(B) attempts to destroy an active object, if destroyed, will causevirtual Overhang Reference (dangling reference)
C) attempting to destroy the same object multiple times
2) Some benefits of garbage collector
A) Each object will be destroyed and its destructor will be called
B) Each object is destroyed only once
C Each object is destroyed only when it is unreachable (unreachable), in other words, any references to that object no longer exist.
The destructor is run only when the object is garbage collected. Some guiding ideas:
1 careful use of destructors, the garbage collector will affect the speed of the program
2 The order of "end" (called "finalization" of the process of invoking the destructor) is not guaranteed, so make sure that the destructor does not depend on each other or overlaps with each other.
second, resource management
Sometimes it is unwise to release a resource with a destructor, and some resources may be too valuable to release immediately after use. In this case, the only option is to release the resources yourself.
The "disposal method" emphasizes the use of the side instead of. In other words, a disposal method can use any valid C # method name, rather than a specially named disposal method.
2.1 Disposal method

TextReader reader= New StreamReader (fileName);
string line;
while (Line=reader. ReadLine ())!=null)
{
    Console.WriteLine (line);
}
Reader. Close ();

It is possible to run reader. Before close (), the program throws an exception, and eventually consumes the file handle resource and cannot open any more files.
2.2 Disposal method of abnormal security
To ensure that the disposal method, such as close, is always invoked-whether or not an exception occurs-one way is to call the disposal method in a finally block.

TextReader reader= New StreamReader (fileName);
Try
{
    string line;
    while (Line=reader. ReadLine ())!=null)
    {
         Console.WriteLine (line);
    }
}
Finally
{
    reader. Close ();
}
It is possible to use the finally block, but because it has several drawbacks, it is not an ideal solution:
1 If multiple resources must be destroyed, the situation will soon become unmanageable (and eventually a large number of nested try and finally blocks will be obtained)
2 It cannot create an abstraction of the solution
3 The reference to the resource remains in the scope after the finally block
three, using statement (recommended scheme)
A using statement provides a well-defined mechanism for controlling the lifetime of a resource. You can create an object that will be destroyed at the end of the using statement block.
A variable declared in a using statement must be a type that implements the IDisposable interface. The IDisposable interface contains only one named Dispose method in the System namespace. The using statement has the following features:
1 the need to dispose of multiple resources, with good scalability
2 does not affect the logic of the program code
3 to the problem of good abstraction, to avoid duplication of coding
4 is very robust, the variable declared in the using statement cannot be used after the using statement is completed because it is no longer in scope. If used consistently, a compile-time error occurs.
Iv. calling the Dispose method from the destructor
1) class implements the IDisposable interface
2 The destructor calls Dispose
3 The Dispose method is a public method that can be invoked at any time
4 The Dispose method can be safely invoked multiple times
5 The Dispose method calls the static method Gc.suppressfinalize
6 all the normal methods of the class are to check whether the object is disposed, and if so, throw an exception.
v. Compulsory garbage collection
You can call the static method System.GC.Collect to invoke the garbage collector in one program. The System.GC.Collect method starts the garbage collector, but the specific recycle process is done asynchronously. When the method ends, the programmer still doesn't know if the object has been destroyed.
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.