C # Programmers are very fortunate relative to C + + programmers, at least we don't have to be bothered with memory leaks (Memory leak), and we don't need to be responsible for allocating and recycling memory. But that doesn't mean we just need to know the syntax of new, and as a serious C # programmer, we should be aware of this and help us write better code.
Main content:
The memory allocation mechanism of the CLR
The CLR's recycling mechanism
Memory allocation mechanism of the CLR
The. NET Framework's garbage collector manages the memory allocation and release of the application. Each time an object is created with the new operator, the runtime allocates memory from the managed heap for that object. As long as the address space is available in the managed heap, the runtime continues to allocate space for the new object.
...
object obj = new object();
...
However, memory is not infinitely large.
public void FillMemory()
{
ArrayList memory = new ArrayList();
// 输出填充前所占内存大小
Console.WriteLine("used memory:" + GC.GetTotalMemory(false));
for (int i = 0; i < 100000; i++)
{
memory.Add(new object());
}
// 输出填充后所占的内存大小
Console.WriteLine("used memory:" + GC.GetTotalMemory(false));
}
Eventually, the garbage collector must perform a recycle to free some memory. The garbage collector optimization engine determines the best time to perform a collection based on the allocation that is in progress. When the garbage collector performs a collection, it examines objects in the managed heap that are no longer being used by the application and performs the necessary actions to reclaim the memory they occupy.
Second, the CLR's memory recovery mechanism
Most of the objects we create in our programs are managed objects that can be automatically reclaimed by GC, but for objects that encapsulate unmanaged resources, we need to explicitly overload the object. Finalize () interface to implement the release of unmanaged resources.
using System;
using System.IO;
public class Foo
{
private SomeComObject _com;
public Foo()
{
_com = new SomeComObject();
}
// some other operation here...
~Foo()
{
// release the unmanaged resource
_com.Close();
}
}