Can you use a constructor FileStreamto ensure that only one process accesses a file at a time? Will the following code work?
public static IDisposable AcquireFileLock() {
IDisposable lockObj;
do {
lockObj = TryOpenLockFile();
if (lockObj == null) Thread.Sleep(100);
}
while (lockObj == null);
return lockObj;
}
private static FileStream TryOpenLockFile() {
try {
return new FileStream(s_LockFileName, FileMode.Create, FileAccess.Read, FileShare.None);
}
catch (IOException) {
return null;
}
}
In particular, is the behavior with FileMode.Createatomic WRTs different processes? Is there anything else I should use?
EDIT: More specifically, this applies to the Microsoft CLR using local files on the same machine.
source
share