C# 存储字节数组时减少内存使用的一种方法

C# 存储字节数组时减少内存使用的一种方法,c#,C#,我是一个初学者,已经学了几天了 private void SendFile(Socket client, string user, string folder1, string folder2, string zipFile) { byte[] zipBytes = File.ReadAllBytes(zipFile); //file string fileInfoStr = user + "," + folder1 + "," + folder2 + ","

我是一个初学者,已经学了几天了

private void SendFile(Socket client, string user, string folder1, string folder2, string zipFile)
{
    byte[] zipBytes = File.ReadAllBytes(zipFile); //file

    string fileInfoStr = user + ","
   + folder1 + ","
   + folder2 + ","
   + Path.GetFileName(zipFile) + ","
   + zipBytes.Length;

    byte[] fileInfo = Encoding.UTF8.GetBytes(fileInfoStr);

    byte[] fileInfoLen = BitConverter.GetBytes(fileInfo.Length);
    var clientData = new byte[4 + fileInfo.Length + zipBytes.Length];

    fileInfoLen.CopyTo(clientData, 0);
    fileInfo.CopyTo(clientData, 4);
    zipBytes.CopyTo(clientData, 4 + fileInfo.Length);

    // Begin sending the data to the remote device.  
    client.BeginSend(clientData, 0, clientData.Length, 0,
new AsyncCallback(SendCallback), client);

    Receive(client);
}
问题是,例如,我尝试发送一个300MB的大型zip文件,内存使用率飙升至600mb+。
我一直在想怎样才能减少内存的使用。谢谢。

您可以通过不使用内存来减少内存使用

比如不使用这样的语句:

byte[] zipBytes = File.ReadAllBytes(zipFile);
而是使用类似文件流的方法:

const int BufSize = 32 * 1024; // 32K you can also increase this
using (var fileStream = new FileStream(zipFile, FileMode.Open))
{
    using (var reader = new BinaryReader(fileStream))
    {
        var chunk = new byte[BufSize];
        var ix = 0;
        var read = 0;
        while ( (read = reader.Read(chunk,ix,BufSize))>0)
        {
            ix += read;
            client.Send(chunk);
        }
    }
}

您将块读入内存,而不是整个文件。并将其分块发送。

尽量使用using释放内存您正在使用file.ReadAllByteszipFile将整个300MB文件读取到内存中,然后您正在分配另一个300MB字节数组,再加上几个新字节[4+fileInfo.Length+zipBytes.Length]。您必须以较小的块读取文件,然后一次发送一个,以防止占用如此多的内存。这是否回答了您的问题?或