使用 MMF 时获取文件读取权限
我有两个进程。一种是使用 .NET 4 MemoryMappedFiles 写入内存映射文件,另一种是使用 .NET 3.5 (MONO) 中的 FileStream 读取文件。当我获得许可时,一切正常,读取或写入文件没有问题。问题是要获得许可。
写入 MMF(写入器):
MemoryMappedFile.CreateFromFile
(filenameToMap, FileMode.Create, "Something",
Marshal.SizeOf(objectToMap), MemoryMappedFileAccess.ReadWrite);
读取 MMF(读取器):
new FileStream(filenameToMap, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
首先启动写入器,然后启动读取器。
我使用这种幼稚的方法对其进行了测试:
while (true)
{
try
{
new FileStream(mapPath + "map.mp", FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
break;
}
catch { }
}
大约 10 秒后,读者通常会获得许可,一切都会顺利进行。如果我捕获异常,它会抛出:
IOException:路径上的共享冲突 C:\路径位于 System.IO.FileStream..ctor (System.String路径,FileMode模式, FileAccess 访问、FileShare 共享、 Int32 bufferSize,布尔匿名, FileOptions 选项)[0x00000] 中 :0
知道为什么这两个进程从一开始就不能正确共享文件吗?
I have two processes. One writing in a memory mapped file using .NET 4 MemoryMappedFiles and the other reading the file using FileStream in .NET 3.5 (MONO). Everything works fine when I get the permission, no problem reading or writing the file. The problem is to obtain a permission.
Writing MMF (the Writer):
MemoryMappedFile.CreateFromFile
(filenameToMap, FileMode.Create, "Something",
Marshal.SizeOf(objectToMap), MemoryMappedFileAccess.ReadWrite);
Reading MMF (the Reader):
new FileStream(filenameToMap, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
First I start the Writer, then the Reader.
I tested it using this naive approach:
while (true)
{
try
{
new FileStream(mapPath + "map.mp", FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
break;
}
catch { }
}
After roughly 10 seconds, the Reader usually gets permission and everything runs smooth. If I would catch the exception, it would throw:
IOException: Sharing violation on path
C:\path at
System.IO.FileStream..ctor
(System.String path, FileMode mode,
FileAccess access, FileShare share,
Int32 bufferSize, Boolean anonymous,
FileOptions options) [0x00000] in
:0
Any idea why these two processes don't share the file properly from beginning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论