Can I use the FileStream
constructor to ensure only one process accesses a file at a time? Will the following code work?
public static IDisposable AcquireFileLock() {
IDisposable lockObj;
do {
// spinlock - continually try to open the file until we succeed
lockObj = TryOpenLockFile();
// sleep for a little bit to let someone else have a go if we fail
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 behaviour with FileMode.Create
atomic WRT other processes? Is there something else I should be using?
EDIT: to be more specific, this is on the Microsoft CLR using local files on a single machine.