在 .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
}
关于c# - 如何共享对内存映射文件的只读访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24435260/