我有两个 .NET 4.0 WinForms 应用程序,它们(主要)从共享的 MemoryMappedFiles 读取地理数据。最终用户可以自由地启动其中一个或另一个应用程序,或者同时运行这两个应用程序。打开的第一个应用程序创建名为 MemoryMapFile-s,第二个应用程序打开已经存在的应用程序。但是,打开现有的命名 MemoryMappedFile 似乎是不可靠的。它在大约 80% 的情况下有效,但在大约 20% 的情况下它因 FileNotFoundException 而失败。症状不能安全地重现,当它失败和成功时,它似乎是纯粹的运气。
这是两个应用程序用来获取 MemoryMappedFiles 的代码:
private static MemoryMappedFile GetMemoryMappedFile(string filePath)
{
string mapName = filePath; // I have also tried here @"Global\myfile", no difference
MemoryMappedFile mmf = null;
try
{
// When the first app executes this step, it always succeeds.
// When the second app comes here, it fails as it should.
mmf = MemoryMappedFile.CreateFromFile(filePath, FileMode.OpenOrCreate,
mapName, HundredMB, MemoryMappedFileAccess.ReadWrite);
}
catch (IOException)
{
try
{
// Opening the already existing named MemoryMappedFile by the SECOND app.
// This line fails about 20% of the time.
mmf = MemoryMappedFile.OpenExisting(mapName,
MemoryMappedFileRights.ReadWrite);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Yet again, could not open MMF. Life sux.");
}
}
return mmf;
}