Analysis of C # data types and memory management mechanism (2)

Source: Internet
Author: User

1. Object Class re-analysis:

System. Object is the base class of all. Net classes, including value type and reference type. Why does the value type inherit from System. Object? Isn't the Object of the reference type? This involves an interesting and magical mechanism of. Net-box and Unbox ). This will be mentioned later.

Object is the base class of all classes and structures. All classes inherit from Object classes, while struct inherits from System. ValueType, while System. ValueType inherits from objects.

Well, since the Object class level is so high, what Members should it contain? Of course, there will be no member variables, which cannot exist in such advanced classes and is not necessary. However, the Object class defines many common methods. If the newly created class does not reload these methods, your new class will automatically inherit these methods of the Object class. These general methods are listed in the following table for your reference:

Method name prefix Modifier
String ToString () public virtual returns the string representation of the object
Int GetHashTable () public virtual is used to implement Dictionary (hash). This is the object used in the collection (hash ).
Bool Equals (object obj) public virtual equal comparison of object instances
Bool Equals (object obj1, object obj2) public static performs equal Comparison on object instances
Bool ReferenceEquals (object obj1, object obj2) public static compares whether two references point to the same object
Type GetType () public returns detailed information about the object Type
Object MemberwiseClone () protected for object superficial Replication
Void Finalize () protected virtual destructor

We have seen some modifiers such as virtual, static, and protected. When I learned the C # language mechanism, I made some details about the content, see C # modifier summary.

Let's look at the virtual modifier, which indicates that some methods can be overloaded. For example, ToString. If the classes we define are not specifically declared, they all inherit objects. That is to say, these public methods of the Object exist in every class, whether it is a class in. Net Framework or a custom class.

2. Garbage collection mechanism, dispose () & Finalize ()

In the analysis of C # data types and Memory Management Mechanism (1), I mentioned the. Net garbage collection mechanism. This mechanism is really one of the core content of. Net. Although it cannot be directly used, it is very important to understand it. Avoid many unnecessary errors in the program. Shows the GC process:

We can call garbage collection in the program:

View sourceprint? 1 System. GC. Collect ()

However, please be careful not to call this code, but garbage collection will be able to recycle all unreferenced objects. This is also case-sensitive. Sometimes the set object is released, but the elements in the set are not necessarily released. This also depends on whether the element object has a code scope (in the code, it indicates that it is, leaving a bracket containing the element ). The garbage collection mechanism can manage managed resources and memory very well. However, some problems may occur when processing some unmanaged resources, such as file handles, network connections, databases, and special devices.

(1). Net destructor Finalize ()

View sourceprint? 1 class TestClass

2 {

3 ~ TestClass ()

4 {

5 // implementation

6}

7}

In fact, this destructor will be compiled into the following form when generating IL, And the Finalize method will be automatically generated:

Protescted overide void Finalize ()

{

Try

{

// Destructor execution

}

Finally

{

Base. Finalize ();

}

}

The Destructor will be called before the GC releases the object. Due to the. Net garbage collection mechanism, we cannot control the execution time of the Destructor or predict the destructor. Therefore, if we need to release unmanaged resources, it will be troublesome to put the released operation in the Finalize () of the destructor. There are several main reasons: ① we cannot control the execution of destructor at specific times, so that some important resources should be released immediately after they are used up. ② It is also impossible to control the execution sequence of Finalize. However, some objects are associated and must be released sequentially. ③ Execution of destructor will delay the time for memory release of the object. It is necessary to wait until the second GC to completely release the modified object. ④ The runtime database uses a thread to chain each Finalize method to be executed. This queue will affect the performance.

To sum up, Finalize () is not suitable for the release and final processing of the resource of an object in. Net programs, but also for some operations that require the execution time. C # We recommend using System. IDisposable to replace this destructor. GC mechanism after Finalize is added:

 

(2) IDisposable Interface

IDisposable provides the ability to release unhosted resources at a specified time. This avoids some problems arising from the garbage collection mechanism by destructor. When an object ends, you must explicitly call the Dispose () method to release resources.

View sourceprint? 1 Class TestClass: IDisposable

2 {

3 public void Dispose ()

4 {

5 // implementation

6}

7}

The above is the implementation of the IDisposable interface. In order to make an object always execute the Dispose method, we usually put Dispose () in the Final segment of try/catch, that is, it will be executed in any case, including exceptions. Suppose we have a CriticalResource class, we can do this:

CriticalResource Instance = null;

Try

{

Instance = new CriticalResource;

// Processing code

}

Finally

{

If (Instance! = Null)

Instance. Dispose ();

}

// You can also use the following method to use the using block to reduce the amount of code and achieve the same effect.

Using (CriticalResource Instance = new CriticalResource)

{

// Processing

}
(3) Dual Implementation of Finalize and Dispose
You can use Dispose () as the method to end the object, and Finalize as the security mechanism (no call to Dispose is used as an insurance method ). This method should be the best solution for releasing resources, but it is more complicated. You can refer to the following simple implementation.

View sourceprint? 01 public class CResource: IDisposable

02 {

03 // record whether the Dispose has been executed

04 Private bool isDispose = false;

05 // implement the Dispose method

06 Public void Dispose ()

07 {

08 // release resources

09 Dispose (true );

10 // GC prohibits the use of finalize destructor

11 GC. SuppressDinalize (this );

12}

13

14 protected virtual void Dispose (bool disp)

15 {

16 // no execution of Dispose

17 if (! IsDisposed)

18 {

19 if (disp)

20 {

21 // release managed resources

22}

23 // release unmanaged Resources

24}

25 isDisposed = true;

26}

27

28 ~ CResource ()

29 {

30 Dispose (false)

31}

32

33 public TestMethod ()

34 {

35 // ensure that resources are not released during execution

36 if (isDisposed)

37 {

38 throw new Exception ();

39}

40}

41

42}

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.