Destructors, constructors

Source: Internet
Author: User

Using destructors to free resources

Destructors are used to instantiate an instance of a class.

1) destructors cannot be defined in structs. Destructors can only be used on classes.

2) A class can have only one destructor.

3) destructors cannot be inherited or overloaded.

4) The destructor cannot be called. They are automatically called.

5) destructors have neither modifiers nor parameters.

For example, the following is a declaration of a destructor for a class Car:

[CSharp]View Plaincopy
    1. Class Car
    2. {
    3. <summary>
    4. Destructors
    5. </summary>
    6. ~car ()
    7. {
    8. Cleanup statements ...
    9. }
    10. }
The destructor implicitly invokes the Finalize of the object base class. In this way, the destructor is implicitly converted to the following code: [CSharp]View Plaincopy
    1. protected override void Finalize ()
    2. {
    3. Try
    4. {
    5. Cleanup statements ...
    6. }
    7. Finally
    8. {
    9. Base. Finalize ();
    10. }
    11. }
This means that all instances in the inheritance chain are called recursively to the Finalize method.

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

Programmers cannot control when destructors are called, because this is determined by the garbage collector. The garbage collector checks to see if there are objects that the application is no longer using. If the garbage collector considers an object to be destructor-compliant, the destructor (if any) is called, and the memory of the object is reclaimed. Destructors are also called when the program exits.

You can enforce garbage collection by calling Collect, but in most cases you should avoid doing this because it can cause performance problems.

Typically, the. NET Framework garbage collector implicitly manages memory allocation and deallocation of objects. However, when an application encapsulates unmanaged resources such as Windows, files, and network connections, these resources should be freed using destructors. When an object conforms to a destructor, the garbage collector runs the object's Finalize method.

Although the garbage collector can track the lifetime of an object that encapsulates an unmanaged resource, it does not know how to clean up those resources. 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 the object. Finalize is protected, so it can only be accessed through this class or derived class.

After the object becomes inaccessible, this method is called automatically unless the GC has passed. The SuppressFinalize call exempts the object from finalization. During the shutdown of an application domain, Finalize is automatically called on objects that are not exempt from finalization, even if those objects are still accessible. Automatically calls Finalize only once for a given instance, unless a GC is used. ReRegisterForFinalize re-registers the object and does not call gc.suppressfinalize later.

Each finalize implementation in a derived type must call its base type's finalize implementation. 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 calls the destructor of its base class.

The Finalize operation has the following limitations:

1) The exact time to execute finalizers during the garbage collection process is indeterminate. Resources are not guaranteed to be released at any given time, unless the Close method or the Dispose method is called.

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

3) The thread running the finalizer is unspecified.

In the following exception scenario, the Finalize method may not run complete or may not run at all:

1) Another terminator blocks indefinitely (entering an infinite loop, trying to get a lock that can never be acquired, and so on). Because the runtime tries to run the finalizer to complete, if a finalizer is blocked indefinitely, the other finalizers might not be called.

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

During the shutdown process, the runtime continues to Finalize objects only if 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 execute any active try-finally blocks or finalizers. This behavior ensures process integrity if the finalizer cannot release or destroy resources.

Description: By default, Object.Finalize does not perform any action. It must be overridden by a derived class only if necessary, because if a Finalize operation must be run, recycling in the garbage collection process often takes much longer. If object holds a reference to any resource, Finalize must be overridden by a derived class to dispose of the resource before discarding the object during garbage collection. When a type uses a file handle or database connection, this type must implement Finalize when it recycles unmanaged resources that must be freed when using managed objects. Finalize can take any action, including having the object resurrected (that is, making the object accessible again) after it has been cleaned up during garbage collection. However, the object can only be resurrected once, and in the garbage collection process, Finalize cannot be called on the Resurrection object.

Destructors are C # mechanisms for performing cleanup operations. Destructors provide appropriate protection, such as the automatic invocation of a destructor for a base type. In C # code, Object.Finalize cannot be called or overridden.

Example

The following example verifies that when an object that reconstructs a Finalize method is destroyed, the Finalize method is called. Note that in a product application, the Finalize method is refactored to release the unmanaged resources owned by the object. In addition, C # provides destructors without refactoring the Finalize method.

[CSharp]View Plaincopy
  1. Using System;
  2. Using System.Diagnostics;
  3. public class ExampleClass
  4. {
  5. Stopwatch SW;
  6. Public ExampleClass ()
  7. {
  8. SW = Stopwatch.startnew ();
  9. Console.WriteLine ("Instantiated object");
  10. }
  11. public void Showduration ()
  12. {
  13. Console.WriteLine ("This instance of {0} have been in existence for {1}", this, SW. Elapsed);
  14. }
  15. ~exampleclass ()
  16. {
  17. Console.WriteLine ("Finalizing object");
  18. Sw. Stop ();
  19. Console.WriteLine ("This instance of {0} have been in existence for {1}", this, SW. Elapsed);
  20. }
  21. }
  22. public class Demo
  23. {
  24. public static void Main ()
  25. {
  26. ExampleClass ex = new ExampleClass ();
  27. Ex. Showduration ();
  28. }
  29. }

The output results are as follows:

[Plain]View Plaincopy
    1. Instantiated Object
    2. This instance of ExampleClass have been in existence for 00:00:00.0011060
    3. Finalizing Object
    4. This instance of ExampleClass have been in existence for 00:00:00.0036294


Explicit release of resources

If your application is using expensive external resources, it is recommended to provide a way to explicitly release the resources before the garbage collector releases the objects. This can be done 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 over resources, destructors are a safeguard 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.

Example

Create three classes, these three classes form an inheritance chain. There are destructors for all three of these classes. In Main (), an instance of the most derived class is created. When the program runs, the destructors for these three classes are called automatically and are called in the order from the most derived to the least-derived degree.

[CSharp]View Plaincopy
  1. Class first
  2. {
  3. ~first ()
  4. {
  5. System.Diagnostics.Trace.WriteLine ("First ' destructor is called.");
  6. }
  7. }
  8. Class Second:first
  9. {
  10. ~second ()
  11. {
  12. System.Diagnostics.Trace.WriteLine ("Second s destructor is called.");
  13. }
  14. }
  15. Class Third:second
  16. {
  17. ~third ()
  18. {
  19. System.Diagnostics.Trace.WriteLine ("Third S destructor is called.");
  20. }
  21. }
  22. Class Testdestructors
  23. {
  24. static void Main ()
  25. {
  26. Third T = new third ();
  27. }
  28. }

In the VS Output window (shortcut key Ctrl+w,o) you will see the following information:

[Plain]View Plaincopy
    1. ......
    2. Third ' sdestructor is called.
    3. Second ' Sdestructor is called.
    4. First ' sdestructor is called.
Program "[3796] TestDestructors.vshost.exe: Managed" 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 names 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 information: GC http://msdn.microsoft.com/zh-cn/library/0xy59wtx (v=vs.90). aspx

Destructors, constructors

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.