c# - 如何共享对内存映射文件的只读访问

标签 c# .net memory-mapped-files

在 .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/

相关文章:

.net - CLR 销毁 .NET 对象

c++ - 在虚拟地址空间中使用内存映射文件

c# - WPF 使用资源中的文本颜色

c# - 等号神奇地出现在发送给寻呼机的消息中

c# - Entity Framework + PostgreSQL 代码优先

c# - 如何从 Pocket(稍后阅读)或 Readability 等 HTML 页面中提取文章文本内容?

c# - Entry 获得焦点时隐藏键盘

C# 对象初始值设定项 : Set Property from another one

c++ - 访问共享内存映射文件 View 的数量 (Windows)

c#内存映射文件读取