我使用MemoryMappedFile(MMF)将大文件放入内存中。使用内存限制为32 memory。使用MMF加载50 MMF文件的时间为2-3秒。从MMF读取数据工作良好和快速。对我来说,唯一的问题是:我有一个大项目,在多个地方大量使用BigEndianReader (源自BinaryReader)。我宁愿修改这个类,用MMF调用替换BinaryReader调用,而不是重写代码。有谁知道如何从MMF中创建团队吗?我有IntPtr为MMF,但我不知道如何从它创建流。
发布于 2015-06-02 06:12:20
您必须对Stream进行子类,跟踪流的Position和当前映射的段:
public class MmfStream : Stream
{
private IntPtr currentMap;
private long mapOffset;
private long mapSize;
private long position;Stream基类要求您实现Read和Write方法,因此每当应用程序尝试读取或写入时,都可以使用Marshal.Copy从当前映射段复制数据。
如果流的Position超出了映射段,则创建一个新的映射,并从新映射的段中提供信息。您还必须处理从当前视图和新映射视图访问数据的问题。类似于:
public override int Read(byte[] buffer, int offset, int size)
{
// current position not in current mapping?
if (position < mapOffset)
{
// relocate the view
}
// compute how many bytes can be read from the current segment
int read = Math.Min(size, (mapOffset + mapSize) - position);
// copy those bytes to the buffer
Marshal.Copy(...);
position += read;
if (size > read)
{
// recurse for the remaining bytes
read += Read(buffer, offset + read, size - read);
}
return read;
}(这个代码片段中可能有一次性错误,这只是一个想法的说明)
https://stackoverflow.com/questions/30575167
复制相似问题