如何在C#中使进程(而非线程)同步文件系统访问 [英] How to have processes (not threads) in C# synchronize file system access
问题描述
今天早些时候,我正在调试类似以下的内容:
Earlier today I was debugging something that went a bit like this:
class Foo {
void AccessCriticalSection() {
try {
if (IO.File.Exists("\\path\to\lock.txt")
throw new Exception();
System.IO.File.Create("\\path\to\lock.txt");
criticalSection();
} catch (Exception ex) {
// ignored
}
}
void CriticalSection() {
// banana banana banana
System.IO.File.Delete("\\path\to\lock.txt");
}
}
我们什至不了解这有多可怕……但是,它实际上是在尝试使用名为lock.txt
的文件作为其互斥量.该操作不是原子操作,如果其他进程正在使用它,其他进程只是无法通过关键部分(如果可以相信,它们应该能够在释放锁之后继续运行),等等.它需要修复.
Let's not even get into how terrible this is… but it's essentially trying to use a file called lock.txt
as its mutex. The operation isn't atomic, other processes are just not getting through the critical section if another process is using it (they're intended to be able to continue after the lock is released if you can believe it), etc. etc. Obviously it needs to be fixed.
如何正确获取锁以跨多个进程同步对文件系统的访问?这些进程是同一进程的多个实例,因此它们可以共享某种协议,而不是专门锁定目录(即,它们可以轻松地使用与某些类的所有实例等效的东西锁定在诸如private final static Object lock = new Object();
之类的东西上)来同步对静态方法)
How do I properly obtain a lock to synchronize access to the filesystem across multiple processes? The processes are multiple instances of the same process, so they can share some protocol rather than specifically locking the directory (i.e., they can easily use what is the equivalent to all instances of some class locking on something like private final static Object lock = new Object();
to synchronize access to static methods)