【发布时间】:2013-03-27 15:17:05
【问题描述】:
我们在 MemoryMappedFile 中加载了一个 222MB 的文件,用于访问原始数据。使用 write 方法更新此数据。经过一些计算,数据应重置为文件的原始值。我们目前正在通过释放类并创建一个新实例来做到这一点。 这在很多时候都很顺利,但有时 CreateViewAccessor 会崩溃并出现以下异常:
System.Exception:没有足够的存储空间来处理此命令。 ---> System.IO.IOException: 没有足够的存储空间来处理这个命令。
在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 在 System.IO.MemoryMappedFiles.MemoryMappedView.CreateView(SafeMemoryMappedFileHandle > memMappedFileHandle,MemoryMappedFileAccess 访问,Int64 偏移量,Int64 大小) 在 System.IO.MemoryMappedFiles.MemoryMappedFile.CreateViewAccessor(Int64 offset, Int64 > size, MemoryMappedFileAccess access)
以下类用于访问内存映射文件:
public unsafe class MemoryMapAccessor : IDisposable
{
private MemoryMappedViewAccessor _bmaccessor;
private MemoryMappedFile _mmf;
private byte* _ptr;
private long _size;
public MemoryMapAccessor(string path, string mapName)
{
FileInfo info = new FileInfo(path);
_size = info.Length;
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
_mmf = MemoryMappedFile.CreateFromFile(stream, mapName, _size, MemoryMappedFileAccess.Read, null, HandleInheritability.None, false);
_bmaccessor = _mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.CopyOnWrite);
_bmaccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref _ptr);
}
public void Dispose()
{
if (_bmaccessor != null)
{
_bmaccessor.SafeMemoryMappedViewHandle.ReleasePointer();
_bmaccessor.Dispose();
}
if (_mmf != null)
_mmf.Dispose();
}
public long Size { get { return _size; } }
public byte ReadByte(long idx)
{
if ((idx >= 0) && (idx < _size))
{
return *(_ptr + idx);
}
Debug.Fail(string.Format("MemoryMapAccessor: Index out of range {0}", idx));
return 0;
}
public void Write(long position, byte value)
{
if ((position >= 0) && (position < _size))
{
*(_ptr + position) = value;
}
else
throw new Exception(string.Format("MemoryMapAccessor: Index out of range {0}", position));
}
}
此问题的可能原因是什么?有什么解决方案/解决方法吗?
【问题讨论】:
-
您是否尝试在处理完 MMF 后致电
GC.Collect?该错误通常意味着内存不足。 -
我们最终编写了自己的映射器,将这个文件的块加载到内存中,因此不需要在内存中拥有一大块可用空间。你可以在gist.github.com/luuksommers/af473efe618d589df951查看它