C # Resource release and Dispose, close, and destructor methods

Source: Internet
Author: User

Note: Some of the opinions in this article are wrong, and the reason why we still keep this article is that we need to give an erratum version later. The correct version is here "implementation of standard Dispose mode in C # "

One: What is a resource

Before you start this article, you need some preparation knowledge. The first thing to ask is "what is a resource". After the CLR comes out, Windows system resources begin to be categorized as "unmanaged resources" and "managed resources."

Unmanaged resources are: All window kernel objects (handles) are unmanaged resources, such as for stream, database connections, GDI + related objects, and COM objects, and so on, these resources are not subject to CLR management;

Managed resources are resources that are allocated and freed by the CLR, that is, objects that are new from the CLR.

Second, the way resources are released.

Unmanaged resources: You need to explicitly release, that is, you need to write code release;

Managed resources: There is no need to explicitly release, but if the reference type itself contains unmanaged resources, it needs to be released in a realistic style;

Two: Explicit release of C # implementations

An explicitly released C # implementation, supported by C # syntax, is:

1: Dispose method to implement IDisposable interface;

2: Destruction Method (Terminator);

is not supported by the C # syntax, but the explicit release supported by the contract is:

3: Provide display release methods, such as the commonly used Close method;

Three: The similarities and differences of Dispose, close and destructor methods

However, it is necessary to distinguish the similarities and differences between the 3 ways. First, you cannot call the destructor method. The destructor method is called by the garbage collection mechanism. In other words, you don't know when the destructor is invoked. Strictly speaking, it is only a remedy for the release of resources.

One of the proper measures for releasing resources is to implement dispose of the IDisposable interface for the type. When you need to release the type of resources, the call Dipose method should be displayed. Of course, there is also a C # syntax sugar, that is, using a using block, when leaving the using program block, the CLR automatically calls the Dipose method of the object created by the type.

One might ask why some types need to provide a close method, since the release of the resource can be done in the way of the Dispose method. The difference, or the Convention, is that if you look closely at these types: they basically only expose the Close method, they all implement the IDisposable, but both hide the Dispose method. In the case of the socket class, it:

1: Provide public void Close ()

Public void Close () { ///... ((IDisposable) this). Dispose (); //.... }

2: Provide an explicit void IDisposable.Dispose ()

void idisposable.dispose () { this. Dispose (true); Gc. SuppressFinalize (this);}

3: Provides protected virtual void Dispose (bool disposing). The real resource release code is put here.

So in theory, to provide the Dispose method that the Close method ultimately uses, the reason for this is because these types are explicitly implemented IDisposable, and when these dispose methods are called, they must complete a transformation, such as:

((IDisposable) New A ()). Dispose ();

To avoid transformation, the Close method is provided to avoid developers who are unfamiliar with C # syntax to release resources more intuitively.

In the example above, you may have noticed that the IDisposable.Dispose method contains a sentence:

Gc. SuppressFinalize (this);  

This tells the CLR that it is no longer necessary to invoke the destructor (finalizer) when it is garbage collected. Yes, because you have manually freed up resources. This also verifies from another aspect that the destructor is only a remediation mechanism for releasing resources. Because if you forget close or Dispose, the CLR will do it for you when it's garbage collected. Looking at the destructor of the socket, you will understand this very well.

~Socket () { this. Dispose (false);}

Yes, the destructor call is also dispose.

Note 1: This article brings several arguments

1: Whether the managed resource itself needs to be explicitly freed. The answer is clearly: no need;

2: If the reference type object is no longer required, do you need an explicit =null; the answer is: even if you do not, the GC will be garbage collected.

3: Dividing managed resources into reference-type resources and value-type resources This classification method is problematic, or wrong. The correct taxonomy should be stack resources and heap resources. The thread stack holds the arguments of the method and local variables inside the method. The heap holds the type object itself and the two additional members of the object: the type object pointer and the synchronization block index.

The 4:dispose method itself is used to allow you to place resource cleanup code. Obviously, an empty method does not mean that the cleanup work itself, actually performing the cleanup is your specific code.

NOTE 2: Recommended dipose mode implementation

such as: base class

Code Classclassshoulddisposebase:idisposable {Public voidDispose () {This. Dispose (True); Gc. SuppressFinalize (this protected virtual void Dispose (bool disposing) {if ( disposing) {// perform basic cleanup code }}
~classshoulddisposebase () {thisfalse} /span>

Sub-class:

Code ClassClassshoulddispose:classshoulddisposebase {Protected Virtual voidDispose (booldisposing) {If(disposing) {// Execute sub-class cleanup code // else {// }}
public void Close () {// Call the Dispose method of this class or base class // other code }} /span>

C # Resource deallocation and Dispose, close, and destructor methods

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.