A way to decrease memory usage when storing byte array
我是一个初学者,现在已经学习了几天
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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 | byte[] zipBytes = File.ReadAllBytes(zipFile); |
而是使用FileStream之类的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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); } } } |
您将块读入内存,而不是整个文件。并分块发送。