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

时间:2019-11-16 09:34:45

标签: 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 + ","
   + 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);
}

问题是例如我尝试发送一个大的zip文件(300mb),内存使用高达600mb +。 我被困在如何减少内存使用上。谢谢。

1 个答案:

答案 0 :(得分:0)

通过不使用内存来减少内存使用量。

就像不使用这样的语句:

byte[] zipBytes = File.ReadAllBytes(zipFile);

您可以使用FileStream之类的方法:

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);
        }
    }
}

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