在Windows 7(或服務器)框上,UNC共享上有一個文件夾(跨機器UNC,而不是 localhost)。我們重命名該文件夾,然後檢查新文件夾位置是否存在文件。即使存在,File.Exists也需要將近5秒才能返回true。文件夾重命名後文件存在檢查返回UNC共享上的一個不正確的值
可以在https://github.com/davidebbo/NpmFolderRenameIssue上找到完整的repro。這裏是核心代碼:
// This file doesn't exist yet
// Note that the presence of this existence check is what triggers the bug below!!
Console.WriteLine("Exists (should be false): " + File.Exists("test/test2/myfile"));
// Create a directory, with a file in it
Directory.CreateDirectory("test/subdir/test");
File.WriteAllText("test/subdir/test/myfile", "Hello");
// Rename the directory
Directory.Move("test/subdir/test", "test/test2");
var start = DateTime.UtcNow;
// List the files at the new location. Here, our file shows up fine
foreach (var path in Directory.GetFiles("test/test2"))
{
Console.WriteLine(path);
}
for (; ;)
{
// Now do a simple existence test. It should also be true, but when
// running on a (cross machine) UNC share, it takes almost 5 seconds to become true!
if (File.Exists("test/test2/myfile")) break;
Console.WriteLine("After {0} milliseconds, test/test2/myfile doesn't show as existing",
(DateTime.UtcNow - start).TotalMilliseconds);
Thread.Sleep(100);
}
Console.WriteLine("After {0} milliseconds, test/test2/myfile correctly shows as existing!",
(DateTime.UtcNow - start).TotalMilliseconds);
所以它看起來像最初的生存確認導致緩存,造成這種虛假行爲存在的價值。
問題:這是什麼解釋?什麼是避免它的最好方法?
注意:在Windows上使用npm(節點包管理器)時,最初出現此問題。我在這裏的代碼是repro的C#端口。有關原始Node/npm問題,請參閱https://github.com/isaacs/npm/issues/2230。目標是找到解決問題的方法。
請注意,調用'File.Exists'不會解決可能的競爭條件。我不確定這裏是否有必要。無論你在做什麼以響應'File.Exists',你都可以響應一個異常。 – 2012-03-08 08:05:19
你可以看到這種行爲與各種網絡文件系統,雖然Win7是相當極端的價值緩存多久......用win2k8我看到這很少,而與Win7它是相當「正規」......我懷疑一些MS文件系統開發可以回答你的問題...得到一些幫助,因此你需要更清楚地描述你的目標IMO ... – Yahia 2012-03-08 08:07:16
@Cody:請注意我在這裏關注你。如果Directory.GetFiles()列出它,File.Exists返回true似乎是合理的,否? – 2012-03-08 08:09:32