问题
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 is currently held on the file
try
{
fs.Lock( RESERVED_BYTE, 1 );
fs.Unlock( RESERVED_BYTE, 1 );
rc = 1;
}
catch
{
rc = 0;
}
QUESTION:
My goal is to eliminate the try/catch block. Is there some better way to see if the lock exists?
EDIT:
Note: This question is not about if the file exists. I already know it does. It is about synchronizing write access.
回答1:
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).
回答2:
Personally I would just catch a locked file when trying to open it. If it's unlocked now, it may be locked when you try to open it (even if it's just a few ms later).
回答3:
My goal is to eliminate the try/catch block
Remember, the file system is volatile: just because your file is in one state for one operation doesn't mean it will be in the same state for the next operation. You have to be able to handle exceptions from the file system.
回答4:
In some circumstances you can also use WCT, it's usually implmented by debugger's or profilers, however it can be used from any code as the usual debugger requirement of being the thread which has the debug port open is not a pre-requisit. As such WCT is a very comprehensive and precise information regarding lock contention.
A managed example (all-be-it somewhat trickey), show's utility for this specific sub-set of the native debug API's on the CLR.
回答5:
I don't think it's possible without try, catch.
来源:https://stackoverflow.com/questions/698442/using-c-sharp-is-it-possible-to-test-if-a-lock-is-held-on-a-file