C # static constructors and destructor fragment cognition

Source: Internet
Author: User

First, Static constructors

A class can have a static constructor that implements the following source code. Static constructors have the following characteristics:

1), static constructors cannot have modifiers (retouch characters)

2), static constructors cannot have parameters

3), cannot be called--when instantiating a class, the static constructor is called actively

4), only static members of the class can be initialized

  Public classQueueclass { Public stringName {Get;Set; }  Public Static intAge {Get;Set; }  PublicQueueclass () {}StaticQueueclass () {//Name = "";//static constructors cannot initialize non-static membersAge =Ten; Console.WriteLine (@"I am a static destructor (constructor), I have the following characteristics: \1), no parameter, no modifier (retouch character), cannot be called, the class is instantiated, the static constructor is called automatically, 2), only static members can be initialized;"); }~Queueclass () {Console.WriteLine ("I am a destructor (deconstruction), please note that I want to reclaim the user code snippet for unmanaged Resources! "); }    }

II. application of destructors and garbage collector in C # (this paragraph is from: http://www.cnblogs.com/kiwi/archive/2012/04/05/2433709.html)

A destructor is a method member that implements an instance of burning a class. Destructors cannot have parameters, cannot have any retouch characters, and cannot be called. Since the object of the destructor is the opposite of the structure function, prefix ' ~ ' is added to the difference.

While C # (and indeed the CLR) provides a new mechanism for memory governance---active memory governance (Automatic management), the release of resources can be done proactively through the "garbage collector", which generally does not require user intervention, In some special cases, however, destructors are needed, such as the release of unmanaged resources in C #.

The release of resources is generally done voluntarily through the ' garbage collector ', but there are still some places to be aware of in particular:

1. References to value types and reference types do not require any ' garbage collector ' to release memory, since they are actively releasing the occupied memory when they are scoped, since they are kept in the stack;

2. Only the object instance to which the reference type's reference is directed remains in the heap, and the heap is a free storage space, so it does not have a lifetime like ' stack ' (the ' stack ' element pops up to the end of the lifetime, which represents the release of the memory), and be mindful that the ' garbage collector ' Only works on this area;

However, in some cases, when an unmanaged resource needs to be released, it must be addressed by writing code. Typically, the destructor is applied to release the unmanaged resource, and the code snippet for releasing the unmanaged resource, written by the user, is placed in the destructor. It should be noted that if a class is not applied to an unmanaged resource, then the destructor must not be defined, because the object fulfills the destructor, then the ' garbage collector ' calls the destructor before releasing the managed resource, and then the second time actually releases the managed resource, Two delete actions are more expensive than once.

Iii. managed resources and unmanaged resources (this paragraph from: http://www.cnblogs.com/nzbbody/archive/2012/01/18/2325335.html)

Managed resources: generally refers to memory resources that are controlled by the CLR, which are managed by the CLR. Can be thought of as a resource in a. NET class library.

Unmanaged resources: Resources that are not controlled and managed by the CLR, such as file streams, database connections, network connections, System window handles, printer resources, and so on, are generally not present on the heap. A set of APIs that can be considered operating system resources.

For managed resources, the GC is responsible for garbage collection. For unmanaged resources, the GC can track the lifetime of an unmanaged resource, but does not know how to release it, and it is manually released.

This paragraph from: http://blog.csdn.net/zlwzlwzlw/article/details/7918633

Managed resources are referred to as. NET resources that can be reclaimed automatically, primarily the memory resources allocated on the managed heap. The collection of managed resources does not require manual intervention, and the. NET runtime is recycled in a suitable call to the garbage collector.

Unmanaged resources are referred to as. NET does not know how to recycle resources, the most common type of unmanaged resources is to wrap the operating system resources of objects such as files, Windows, network Connections, database connections, brushes, icons and so on. This type of resource, the garbage collector calls the Object.Finalize () method when it cleans up. By default, the method is empty, and for unmanaged objects, you need to write code in this method that reclaims the unmanaged resources so that the garbage collector correctly reclaims the resources.

In. NET, the Object.Finalize () method cannot be overloaded, and the compiler automatically generates the Object.Finalize () method based on the destructor of the class, so for classes that contain unmanaged resources, you can place the code that frees the unmanaged resources in the destructor.

Note that managed resources cannot be freed in a destructor because the destructor is called by the garbage collector, and it is possible that the managed resources contained by the class have been reclaimed before the destructor call, leading to unpredictable results.

Originally, unmanaged resources can be recycled by the garbage collector, but unmanaged resources are generally limited and valuable, and the garbage collector is automatically called by the CRL, so that unmanaged resources are not guaranteed to be released in a timely manner, so a Dispose () method is defined. Allows the user to manually release unmanaged resources. The Dispose () method frees both the managed and unmanaged resources of the class, and the garbage collector does not recycle this instance again after the consumer calls this method manually. The Dispose () method is called by the consumer, and when invoked, both the managed and unmanaged resources of the class must not be reclaimed, so both resources can be reclaimed at the same time.

Microsoft has specifically defined an interface for the collection of unmanaged resources: IDisposable, which contains only one Dispose () method. Any class that contains unmanaged resources should inherit this interface.

In a class that contains unmanaged resources, the standard practice for resource deallocation is:

(1) Inherit IDisposable interface;

(2) Implement the Dispose () method, in which the managed and unmanaged resources are freed, and the object itself is removed from the garbage collector (the garbage collector is not reclaiming this resource);

(3) Implement a class destructor in which to release unmanaged resources.

When used, the display calls the Dispose () method, which releases resources in a timely manner, improves performance by removing the execution of the Finalize () method, and if the call to Dispose () method is not displayed, the garbage collector can also release unmanaged resources through destructors. The garbage collector itself has the ability to reclaim managed resources, guaranteeing the normal release of resources, except that recycling by the garbage collector can lead to a waste of non-timely releases of unmanaged resources.

in. NET, you should use as little as possible to free up resources with destructors. Objects without destructors are removed from memory in a single processing of a garbage processor, but objects with destructors require two of times, the first time the destructor is called, and the object is deleted the second time. And having a large number of release resource codes in a destructor can reduce the efficiency of the garbage collector and affect performance. So for objects that contain unmanaged resources, it is best to call the Dispose () method in a timely manner to reclaim resources instead of relying on the garbage collector.

There it is. NET is a resource-freeing mechanism for classes that contain unmanaged resources, and the class is a resource-safe class as long as the code is written according to the steps required above.

Here is an example to summarize. NET unmanaged resource recovery mechanism:

public class Baseresource:idisposable

{

Privateintptr handle; Handle, which belongs to an unmanaged resource

Privatecomponet comp; components, managed resources

Privateboo isdisposed = false; Flag of whether the resource has been freed

Publicbaseresource

{

}

Implementing interface Methods

By the consumer of the class, the call is displayed externally, releasing the class resource

Publicvoid Dispose ()

{

Dispose (true);//releasing managed and unmanaged resources

Removes an object from the list of garbage collector chains.

Thus, when the garbage collector works, only the managed resources are freed, not the destructor of this object

Gc. SuppressFinalize (this);

}

Called by the garbage collector to release unmanaged resources

~baseresource ()

{

Dispose (false);//Release unmanaged Resources

}

A parameter of true means that all resources are freed and can only be invoked by the consumer

A parameter of false means that the unmanaged resource is freed and can only be called automatically by the garbage collector

If the subclass has its own unmanaged resource, you can overload the function to add your own unmanaged resource's release

Remember, however, that overloading this function must ensure that the base class's version is called to ensure that the base class's resources are properly freed

protectedvirtual void Dispose (bool disposing)

{

if (!this.disposed)//If the resource is not released this decision is mainly used to prevent the object from being released multiple times.

{

If (disposing)

{

Comp.dispose ();//Release managed resources

}

CloseHandle (handle);//Release unmanaged Resources

Handle= IntPtr.Zero;

}

this.disposed= true; Identifies that this object has been disposed

}

}


Destructors can only be called by the garbage collector.

The Despose () method can only be called by the consumer of the class.

In C #, any class that inherits the IDisposable interface can use a using statement, allowing the system to call the Dispose () method automatically after it goes out of scope.
A resource-safe class that implements the IDisposable interface and destructor. Provides manual release of resources and automatic release of resources by the system.

C # static constructors and destructor fragment cognition

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.