Location>code7788 >text

Two ways to free .Net memory management

Popularity:211 ℃/2024-08-03 08:50:11

In .Net, resource recovery mainly refers to memory management and the release of unmanaged resources. Two main ways of handling them are provided respectively:

  1. Garbage Collection (GC)
  2. Confirmatory Resource Release (DRD)

Links to relevant documents on the official website:/zh-cn/dotnet/standard/managed-code

Garbage Collection

Garbage collection is a mechanism that automatically handles memory management at the .NET runtime. It is responsible for detecting objects that are no longer being used by the application and freeing the memory occupied by these objects.

Features:

  • Runs automatically and does not need to be explicitly called by the developer
  • Triggered when out of memory
  • Free managed memory (i.e., memory allocated through the .NET inner village)
  • Memory is not guaranteed to be freed immediately, but rather periodically, depending on memory pressures

Limitations of garbage collection:

  • Unable to handle unmanaged resources such as file handles, database links, Graphics Device Interface (GDI) objects, etc.
  • May cause the application to pause briefly (GC pause)

Deterministic resource release

For unmanaged resources, .NET provides a deterministic resource release mechanism, usually via theIDisposableInterface Implementation.

IDsposable interface:

  • When an object implements theIDsposableinterface, meaning it holds resources that need to be manually released
  • realizationIDsposableobject must override theDisposemethod to clean up the unmanaged cache

utilizationusingStatements:

  • utilizationusingstatement to automatically release the implementation of theIDsposableThe resources held by the objects of the
  • usingstatement ensures that even in the event of an exception, theDisposemethod will also be called

Example.StreamReaderRealizedIDsposableinterface. This is accomplished by using theusingstatement, when theStreamReaderWhen an object is out of scope, theDisposemethod is automatically called, which frees the file handle.

using System;
using ;

class Program
{
    static void Main()
    {
        // utilization using statement to automatically release the StreamReader existing resources
        using (StreamReader reader = new StreamReader(""))
        {
            string line;
            while ((line = ()) != null)
            {
                (line);
            }
        }

        // 如果没有utilization using statement,Needs to be called manually Dispose
        // StreamReader reader = new StreamReader("");
        // try
        // {
        // string line;
        // while ((line = ()) != null)
        // {
        // (line);
        // }
        // }
        // finally
        // {
        // ();
        // }
    }
}