In .Net, resource recovery mainly refers to memory management and the release of unmanaged resources. Two main ways of handling them are provided respectively:
- Garbage Collection (GC)
- 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 theIDisposable
Interface Implementation.
IDsposable interface:
- When an object implements the
IDsposable
interface, meaning it holds resources that need to be manually released - realization
IDsposable
object must override theDispose
method to clean up the unmanaged cache
utilizationusing
Statements:
- utilization
using
statement to automatically release the implementation of theIDsposable
The resources held by the objects of the -
using
statement ensures that even in the event of an exception, theDispose
method will also be called
Example.StreamReader
RealizedIDsposable
interface. This is accomplished by using theusing
statement, when theStreamReader
When an object is out of scope, theDispose
method 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
// {
// ();
// }
}
}