C # destructor (destructor) and finalizers (Finalizer) __ Functions

Source: Internet
Author: User
Tags garbage collection inheritance terminates
turn from: http://blog.csdn.net/liuning800203/article/details/6455226
Releasing resources with destructors

Destructors are used to deconstruct instances of classes.

1 The destructor cannot be defined in the structure. Destructors can only be used on classes.

2 A class can have only one destructor.

3 cannot inherit or overload a destructor.

4 cannot invoke the destructor. They are called automatically.

5 The destructor has neither modifiers nor parameters.

For example, the following is a declaration of the destructor of the class car:[CSharp]View plain Copy class Car {///<summary>///destructor///</summary> ~car () {   Cleanup statements ...} The destructor implicitly calls Finalize of the object base class. In this way, the destructor is implicitly converted to the following code:[CSharp]View plain copy protected override void Finalize () {try {//Cleanup statements ...} finally {base.         Finalize (); This means that the Finalize method is called recursively for all instances in the inheritance chain.

Description: Do not use empty destructors. If the class contains a destructor, an item is created in the Finalize queue. When the destructor is called, the garbage collector (GC) is invoked to process the queue. If the destructor is empty, it can only cause unnecessary performance losses.

The programmer has no control over when the destructor is invoked because it is determined by the garbage collector. The garbage collector checks for objects that are no longer in use by the application. If the garbage collector considers an object to conform to the destructor, call the destructor (if any) to reclaim the object's memory. The destructor is also called when the program exits.

Garbage collection can be enforced by invoking Collect, but in most cases this should be avoided because of performance problems.

In general, the. NET Framework garbage collector implicitly manages the memory allocation and release of objects. However, when an application encapsulates unmanaged resources such as Windows, files, and network connections, you should use destructors to release these resources. When an object conforms to the destructor, the garbage collector runs the Finalize method of the object.

Although the garbage collector can track the lifetime of an object that encapsulates an unmanaged resource, it does not know how to clean up the resources specifically. Common unmanaged sources are: ApplicationContext, Brush, Component, ComponentDesigner, Container, Context, Cursor, FileStream, Font, Icon, Image, Matrix, Object, OdbcDataReader, OleDbDataReader, Pen, Regex, Socket, StreamWriter, Timer, Tooltip and so on.


Object.Finalize Method

Allows object to attempt to free resources and perform other cleanup operations before garbage collection reclaims Object. Finalize is protected and can only be accessed through this class or derived classes.

When an object becomes inaccessible, this method is called automatically unless the GC is passed. The SuppressFinalize call eliminates the end of the object. During the shutdown of an application domain, Finalize is automatically invoked for objects that do not have an exemption from finalization, even if those objects are still accessible. Only the Finalize once is automatically invoked for a given instance, unless GC is used. ReRegisterForFinalize the object again, and the gc.suppressfinalize is not called later.

Each finalize implementation in a derived type must call a finalize implementation of its base type. This is the only case where the application code is allowed to call Finalize.

Note: The C # compiler does not allow you to implement the Finalize method directly, so the C # destructor automatically invokes the destructor of its base class.

The Finalize operation has the following limitations:

1 The exact time to execute finalizers during garbage collection is indeterminate. The resource is not guaranteed to be freed at any particular time unless the Close method or Dispose method is called.

2 Even if an object references another object, there is no guarantee that the finalizer of two objects will run in any particular order. That is, if object A has a reference to object B, and both have finalizers, object B may have ended when object A's finalizer starts.

3 The thread running the finalizer is unspecified.

In the following exceptional cases, the Finalize method may not run complete or may not run at all:

1 Another finalizer blocks indefinitely (into an infinite loop, trying to get locks that are never available, and so forth). Because the runtime attempts to run finalizers to complete, if a finalizer blocks indefinitely, other finalizers may not be invoked.

2 The process terminates, but does not give the runtime the opportunity to clean up. In this case, the first process termination notification at run time is the DLL_PROCESS_DETACH notification.

During the shutdown process, the Finalize object continues only when the number of objects that can be terminated continues to decrease.

If a finalize or finalize override throws an exception and the runtime is not hosted in an application that overrides the default policy, the runtime terminates the process and does not perform any active try-finally blocks or finalizers. This behavior ensures process integrity if the finalizer cannot release or destroy the resource.

Description: By default, Object.Finalize does not perform any action. It must be overridden by a derived class only if necessary, because the collection in the garbage collection process often takes much longer if the Finalize operation must be run. If object holds a reference to any resource, Finalize must be overridden by a derived class so that the resources are freed before the object is discarded in the garbage collection process. When a type uses a file handle or a database connection, the type must implement Finalize when the unmanaged resource that must be freed when the managed object is reclaimed. Finalize can take any action, including the resurrection of the object (that is, making the object accessible again) after scavenging the object during the garbage collection process. However, the object can only be resurrected once, and Finalize can not be invoked on the Resurrection object during the garbage collection process.

A destructor is a C # mechanism that performs cleanup operations. Destructors provide appropriate safeguards, such as automatic invocation of a destructor of a base type. In C # code, Object.Finalize cannot be invoked or overridden. Sample

The following example verifies that the Finalize method is invoked when an object that reconstructs a Finalize method is destroyed. Note that in the product application, the Finalize method is refactored to release the unmanaged resources that the object owns. In addition, C # provides destructors without refactoring the Finalize method.[CSharp]  View plain copy using system;   using system.diagnostics;   public class  ExampleClass   {       Stopwatch sw;        public exampleclass ()        {            sw = stopwatch.startnew ();            console.writeline ("Instantiated object");       }        public void showduration ()        {            console.writeline ("this instance of {0}"  has been in existence for {1} ", &NBSP;THIS,&NBSP;SW. Elapsed);       }       ~exampleclass ()        {           console.writeline ("Finalizing object");     &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SW. Stop ();           console.writeline ("This instance  Of {0} has been in existence for {1} ", &NBSP;THIS,&NBSP;SW. Elapsed);       }  }   public class demo   {       public static void main ()         {           ExampleClass ex = new  ExampleClass ();           ex. Showduration ();       }  }  

The output results are as follows: [plain] view Plain Copy instantiated object This instance of ExampleClass has been in existence for 00 : 00:00.0011060 Finalizing Object This instance the ExampleClass has been in existence for 00:00:00.0036294

explicit release of resources

If your application is using expensive external resources, it is recommended that you provide a way to explicitly release resources before the garbage collector frees objects. You can do this by implementing the Dispose method from the IDisposable interface, which performs the necessary cleanup for the object. This can greatly improve the performance of your application. Even with this explicit control of resources, destructors are a protective measure that can be used to clean up resources when a call to the Dispose method fails.

For more detailed information, see Cleaning Up Unmanaged resources. Sample

Create three classes that comprise a chain of inheritance. All three classes have destructors. In Main (), an instance of the most derived class is created. When the program runs, destructors for these three classes are invoked automatically, and are called from the most derived to the least derived order.[CSharp]  View plain copy class first   {       ~first ()         {            System.Diagnostics.Trace.WriteLine ("the s destructor is called.");        }  }   class second : first   {        ~second ()        {            system.diagnostics.trace.writeline ("Second ' s destructor is  Called. ");        }  }   class third : second   {        ~third ()        {            system.diagnostics.trace.writeline ("Third ' s destructor is  Called. ");        }   }   class testdestructors   {       static  void main ()        {            third t = new third ();       }  }   

In the VS Output window (shortcut key Ctrl+w,o) you will see the following message: [plain] view plain copy ...   Third ' sdestructor is called.   Second ' Sdestructor is called.   The ' sdestructor is called. Program ' [3796] TestDestructors.vshost.exe: Managed ' has exited with a return value of 0 (0x0).


For more information, see the following sections in the C # Language specification:

A) 1.6.7.6 destructor

b) 10.3.9.4 the member name reserved for the destructor

c) 10.13 destructor (Class)

d) 11.3.9 destructor (structure)

The C # Language specification is located in the vc#/specifications/1033/directory under the Visual Studio 2008 installation directory.


See data: Gc http://msdn.microsoft.com/zh-cn/library/0xy59wtx (v=vs.90). aspx
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.