Standard IDispose Mode Analysis

Source: Internet
Author: User

 

DoNet Resources

As we all know ,.. Net memory management is divided into Managed resources and unmanaged resources. The objects in the memory are divided according to these two types of resources, and then the GC is responsible for recycling Managed resources. For unmanaged resources, it requires the programmer to manually release it.

The purpose of Framework designers is to reduce the difficulty for developers to get started, improve development efficiency, and make users pay less attention to "Garbage Collection". However, such encapsulation leads to more and more misuse, even terrible inefficiency. (Here, I emphasize abuse caused by understanding the DoNet garbage collection mechanism .) It is often complained that resources have not been recycled, or they have not been recycled by time point, or that they are inefficient when being created. ("Renewable resources" refers to the resources that have just been completely released. According to the. Net design specifications, improper recycling leads to low efficiency during creation .)

I want to remind you that we need a more correct and perfect way to recycle resources.

 

IDisposable Interface

In the Framework Design, the IDisposable interface's Dispose method is implemented in many places. GC automatically and randomly calls the destructor of a resource to achieve the purpose of automatic garbage collection, this interface is from the System namespace.

Therefore, we generally need to implement the IDisposable interface for our custom classes, and automatic recovery has been completed.

 

Standard IDispose Mode

I am not so arrogant. I have a lot of online related information. writing it down here also makes me more familiar with this mode. After all, understanding is one thing. It is another thing to explain it.

First, reference the IDisposable interface, and then paste the Code directly:

 

# Region standard IDispose mode Private bool disposed = false; Public void Dispose () {Dispose (true); GC. SuppressFinalize (this );}~ XXXXClass () {Dispose (false);} Protected virtual void Dispose (bool disposing) {If (disposed) Return; If (disposing) {If (Resource! = Null) {// Release managed resource} // Release unmanaged resource disposed = true;} # endregion

 

A)! = Null if it is null, you do not need to release it.

B) A. Dispose ();

C) A = null;

Here, I would like to add some more information about the concept of Generation (Thank you @ it is not easy to remind everyone ):

Introduction of MSDN:

It is recommended, but not required, that garbage collectors support object aging using generations. A generation is a unit of measure of the relative age of objects in memory. the generation number, or age, of an object indicates the generation to which an object belongs. objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. objects in the most recent generation are in generation 0.

Http://msdn.microsoft.com/en-us/library/system.gc (v = vs.110). aspx

I can't find more materials at once, because these concepts are obtained from various books and understood by myself. This issue is described in "Writing high-quality code-157 suggestions for improving C # programs.

 

In addition, correct your English mistakes, such as Generation rather than Generate.

 

Optimization of thread security problems

First of all, I would like to thank @ binglin for reminding me that thread security has not been taken into account before, because this application scenario has not been met yet, however, I still benefited a lot from Learning @ binglin qingwu's Dispose mode.

Thread security refers to the status of shared resources generated when multiple threads operate on an Instance at the same time to use its resources. That is to say, thread A/B releases M Resources, thread B/A also requires the release of resources, which leads to repeated release of resources. In severe cases, the empty object method is called, leading to errors, thread security should be considered.

I personally modified the method (https://code.csdn.net/snippets/112056) of @ Bing Lin qingwu this elder brother, if there is a mistake, please refer to the official points.

/*************************************** * ********************* Copyright @ BOCO Group * All Rights Reserved. * Author: Cui Yansong (STEPHEN-PC.Cuiyansong) * Mail: cuiyansong@boco.com.cn * Create Date: 5/23/2014 9:29:46 AM * File Name: DisposePatternBase * CLR Version: 4.0.30319.17929 *************************************** * ********************/using System; using System. collections. generic; using S Ystem. linq; using System. runtime. interopServices; using System. text; namespace BocodeProtobufTest. common {/************************************* **************************************** * *************** Note 1: ensure thread security * System. threading. interlocked. compareExchange (T, T, T) is an atomic operation to ensure thread security. * The http://msdn.microsoft.com/en-us/library/bb297966.aspx * First marks the disposedMark as released to ensure that other threads obtain the disposedMark value as released, and other threads do not perform this operation. * Then, determine whether the previous value of disposedMark is not released. If yes, execute Dispose. ** Note 2: differentiate the release methods of managed and unmanaged Resources * If you execute manual release (directly call the Dispose method of the class), you need to release all the resources; * if a program executes a destructor, it does not need to release managed resources because in most cases managed resources can be automatically released and when the system executes the Destructor * method, you cannot manually call the Dispose method. **************************************** **************************************** * *********/Public abstract class DisposePatternBase: IDisposable {# region Public Properties # endregion Public Properties # region Private Properties // <summary> // A private property indicate whether resource have been diposed. /// </summary> /// <remarks> // 0 --- Not Released ///1 --- Released // </remarks> Private int disposedMark = 0; # endregion Private Properties # region Constructor // <summary> // automatically called when the system destroys an object /// </summary> ~ DisposePatternBase () {// atomic operation to ensure thread security. Var original = System. Threading. Interlocked. CompareExchange (ref disposedMark, 1, 0); if (original! = 0) return; Dispose (false) ;}# endregion Constructor # region Public Method /// <summary> // external call (manual) dispose method /// </summary> public void Dispose () {// atomic operation to ensure thread security. Var original = System. Threading. Interlocked. CompareExchange (ref disposedMark, 1, 0); if (original! = 0) return; Dispose (true); GC. suppressFinalize (this);} protected abstract void Dispose (bool disposing); # endregion Public Method} public class DisposePatternDemo: DisposePatternBase {private SafeHandle handle; private IList <byte> source; protected override void Dispose (bool disposing) {if (disposing) {// Release managed resource if (source! = Null & source. Count! = 0) {source = null ;}// Release unmanaged resource if (handle! = Null) handle. Dispose ();}}}

 

 

Reference

Framework Design Guideline)

Http://msdn.microsoft.com/zh-cn/library/System.GC (v = vs.80). aspx

Https://code.csdn.net/snippets/112056

Http://baike.baidu.com/view/1298606.htm? Fr = aladdin

 

 

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.