我的 C# 程序正在使用过多的内存(BinaryReader 进行缓冲)

My C# program is using Excessive Memory (BinaryReader to buffer)

我的程序使用了过多的内存。我正在尝试读取程序的前 512 个字节并将它们存储在内存中。我相信它应该只使用 512 字节的内存,但由于某种原因,它使用了 1GB。

BinaryReader reader;
byte[] buffer = new byte[0];

foreach (IStorageDevice device in Devices)
{
    reader = new BinaryReader(File.Open(device.Location, FileMode.Open));
    buffer = reader.ReadBytes(512);
    reader.Close();
    reader.Dispose();
}

我做的测试只有一个StorageDevice,所以只加载了一个文件。

我似乎找不到它使用这么多内存的原因。任何帮助将不胜感激。

DevicesListIStorageDevice。存储设备只是一个 class 和一个字符串对象,它是读取文件的路径(目前它是我桌面上的 .bin 文件)

public class ROM : IStorageDevice
{
    public string Location { get; set; }

     public ROM(string Location)
     {
         this.Location = Location;
     }
 }

您需要处理您的资源。这就是 using 所做的。当退出 using 块时,流将被释放。

尝试这样的事情:

    byte[] buffer = new byte[512];

    foreach (IStorageDevice device in Devices)
    {
        using (var stream = File.OpenRead(device.Location))
        {
            // Read 512 bytes into buffer if possible.  
            var readCount = stream.Read(buffer, 0, 512);
            StoreData(buffer, readCount); // A method you write to store the data
        }
    }