Can I use FileStream to implement file locking?

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 {
        // 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 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.

+5
source share
2 answers

This will do what you want. FileShare.None- an important part.

- , Mutex , , , ( ). Sleep ( ).

, (Mutex), , , .

+2

, :

  • Windows ( Linux Mono, , , )
  • (SMB , , , NFS WebDAV )
  • IOException, , , , - .
+1

All Articles