我有兩個.NET 4.0 WinForms應用程序(主要)從共享MemoryMappedFiles中讀取地理數據。最終用戶可以自由地啓動應用程序或其他應用程序,或者同時運行這兩個應用程序。第一個打開的應用程序創建命名的MemoryMapFile-s,第二個打開已存在的應用程序。 但是,打開現有的名爲MemoryMappedFile似乎是不可靠的。它可以處理大約80%的案例,但大約有20%的案例使用FileNotFoundException失敗。 症狀不安全可重現,它失敗時,它似乎是純粹的運氣,當它成功。與MemoryMappedFile的不可靠連接
下面是使用這兩個應用得到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;
}
雖然你在技術上是正確的,但這不可能是真正的問題。這些應用程序在啓動時創建/打開MMF,並在它們被殺時關閉它們。此外,這些應用程序的開放時間長。總是第二個失敗,當它被打開。 – user256890 2013-02-14 16:47:28
那麼,你真的沒有提供任何信息來暗示你的代碼沒有出錯和那個。NET Framework的MemoryMappedFile實現有缺陷或沒有正確記錄。你所描述的一切都表明你比其他任何事情都具有競爭條件。 – 2013-02-14 17:20:08
當出現FileNotFoundException時,嘗試使用'File.Exists'來查看它是否返回'false'。這是另一種競爭條件;但如果你的問題確實是一種競爭條件,那麼它應該是'false'而不是'true',並且有20%的失敗率。如果它總是「真」,那麼是的,你的代碼中可能沒有競爭條件。 – 2013-02-14 17:23:18