How do I force release memory occupied by MemoryStream?

后端 未结 4 626
北恋
北恋 2021-02-07 12:02

I have the following code:

const int bufferSize = 1024 * 1024;
var buffer = new byte[bufferSize];
for (int i = 0; i < 10; i++)
{
    const int writesCount = 4         


        
4条回答
  •  伪装坚强ぢ
    2021-02-07 12:36

    Try to force garbage collection when you are sure that it is necessary to clean unreferenced objects.

    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    

    Another alternative is to use the Stream with external storage: FileStream, for example.

    But, in general case, it would be better to use one small enough buffer (array, allocated one time) and use it for read/write calls. Avoid having many large objects in .NET (see CLR Inside Out: Large Object Heap Uncovered).

    Update

    Assuming that the writesCount is the constant, the why not allocate one buffer and reuse it?

    const int bufferSize = 1024 * 1024;
    const int writesCount = 400;
    
    byte[] streamBuffer = new byte[writesCount * bufferSize];
    byte[] buffer = new byte[bufferSize];
    for (int i = 0; i < 10; i++)
    {
        using (var stream = new MemoryStream(streamBuffer))
        {
            for (int j = 0; j < writesCount; j++)
            {
                stream.Write(buffer, 0, buffer.Length);
            }
        }
    }
    

提交回复
热议问题