Using C# is it possible to test if a lock is held on a file

后端 未结 5 1582
我寻月下人不归
我寻月下人不归 2021-01-22 17:51

BACKGROUND: I use an offset into a file and the Filestream lock/unlock menthods to control read/write access. I am using the following code to test if a lock i

5条回答
  •  遥遥无期
    2021-01-22 18:34

    You can call the LockFile Windows API function through the P/Invoke layer directly. You would use the handle returned by the SafeFileHandle property on the FileStream.

    Calling the API directly will allow you to check the return value for an error condition as opposed to resorting to catching an exception.


    Noah asks if there is any overhead in making the call to the P/Invoke layer vs a try/catch.

    The Lock file makes the same call through the P/Invoke layer and throws the exception if the call to LockFile returns 0. In your case, you aren't throwing an exception. In the event the file is locked, you will take less time because you aren't dealing with a stack unwind.

    The actual P/Invoke setup is around seven instructions I believe (for comparison, COM interop is about 40), but that point is moot, since your call to LockFile is doing the same thing that the managed method does (use the P/Invoke layer).

提交回复
热议问题