我尝试编写一个基于MemoryStream和字节数组的.Net 4.8程序。当我尝试将字节数组写入内存流并处置 MemoryStream 时,我发现即使调用了 GC.Collect,也只能释放一半内存。
(当然,我想释放内存而不需要调用GC.Collect,但似乎对于.Net来说这是不可能的)
我该如何解决这个问题? 谢谢。
我的示例代码如下:
static void Main()
{
MemoryStream ms = new MemoryStream()
TestMs(ref ms); // memory is occupied after this call
ms.Dispose();
ms = null;
GC.Collect(); // only half of the memory is freed after this call
GC.WaitForPendingFinalizers();
GC.Collect(); // no memory change compared without the previous GC.Collect
...
}
static void TestMs(ref MemoryStream ms)
{
byte[] b = new byte[100000000];
ms.Write(b, 0, b.Length);
b = null;
}
尝试将其包含在
using
子句中。
例如
static void Main()
{
using (var ms = new MemoryStream())
{
TestMs(ref ms); // memory is occupied after this call
}
}
一旦
TestMs
方法完成并且 ms
变量超出 using
子句的范围,这将分配和释放内存。
GC 然后将执行其需要执行的操作并释放内存。