在使用内存映射文件快速读取.net中的文件流时,我遇到了IOException
的问题,因为两个进程正在读取同一个文件而导致文件锁定。
有几种工厂方法可以生成内存映射文件,如何允许共享readonly
访问?
在使用内存映射文件快速读取.net中的文件流时,我遇到了IOException
的问题,因为两个进程正在读取同一个文件而导致文件锁定。
有几种工厂方法可以生成内存映射文件,如何允许共享readonly
访问?
以下是创建只读内存映射文件到路径的简化工厂方法:
public static MemoryMappedFile MemFile(string path)
{
return MemoryMappedFile.CreateFromFile(
//include a readonly shared stream
File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read),
//not mapping to a name
null,
//use the file's actual size
0L,
//read only access
MemoryMappedFileAccess.Read,
//not configuring security
null,
//adjust as needed
HandleInheritability.None,
//close the previously passed in stream when done
false);
}
using (var memFile = MemFile(path))
using (var stream = memFile.CreateViewStream(0L, 0L, MemoryMappedFileAccess.Read))
{
//do stuff with your stream
}