GC, Dispose, DOTNET

zhaozj2021-02-16  43

About GC

The GC mechanism of .NET has two problems:

First, GC is not able to release all resources. It can't automatically release unmanaged resources.

Second, GC is not real-time, which will cause bottlenecks and uncertainty on system performance.

In order to solve the first problem, .NET provides a destructive function, in the form of ~ classname in C #. If a class defines a destructor, .NET will call the destructor in the first GC, and the second time is truly resource release. This allows us to do some manual resource management operations, manually clean up the non-hosting resources. But if there is no need to define a parsive function, it will have a big impact on performance.

It is not enough to rely on the restructuring function to release the non-hosting resources, which is due to the second problem: GC is not real-time, which causes bottlenecks and uncertainty on system performance. So there is an IDisposable interface, the IDisposable interface defines the Dispose method, which is used to supply the sectors explicitly call to release unmanaged resources.

Usually we should write the program like this:

Public Class Sampleclass: System.idisposable

{

Public void dispose ()

/ / DISPOSE method for programmer explicitly call

{

Dispose (TRUE);

// Call the DISPOSE method with parameters, release managed and unmanaged resources

System.gc.suppressFinalize (this);

/ / Manually call the Dispose release resources, then the destructor is unnecessary, here blocking the GC call destructor

}

Protected Void Dispose (BOOL Disposing)

// Protected Dispose method, guarantees that it will not be called outside.

// Incontine to the BOOL value Disposing to determine if the hosting resource is released

{

IF (Disposing)

{

/ / Add to clean the code of "hosting resources" here, it should be xxx.dispose ();

}

/ / Add to clean the code for "non-hosting resources" here

}

~ SampleClass ()

// For gc call destructor

{

Dispose (false);

// Release unmanaged resources

}

}

In this way, we have called Object.dispose methods as natural in Delphi, even if we forget to call Dispose, GC will help us clean up the non-hosting resources when the object is released. . The role acting as GC is just a means of protection, which should act as this role, we can't over-rely over.

In fact, we should also manually call GC.COLLECT for garbage collection in a timely manner.

转载请注明原文地址:https://www.9cbs.com/read-26496.html

New Post(0)