2

背景: 我使用文件中的偏移量和 Filestream 锁定/解锁方法来控制读/写访问。我正在使用以下代码来测试文件当前是否持有锁

try
{
  fs.Lock( RESERVED_BYTE, 1 );
  fs.Unlock( RESERVED_BYTE, 1 );
  rc = 1;
}
catch
{ 
  rc = 0; 
}

问题:
我的目标是消除 try/catch 块。有没有更好的方法来查看锁是否存在?

编辑:
注意:这个问题与文件是否存在无关。我已经知道确实如此。它是关于同步写访问的。

4

5 回答 5

6

您可以直接通过 P/Invoke 层调用LockFileWindows API 函数。您将使用 FileStream 上的 SafeFileHandle 属性返回的句柄。

直接调用 API 将允许您检查错误条件的返回值,而不是诉诸于捕获异常。


Noah询问调用 P/Invoke 层与调用 try/catch 是否有任何开销。

Lock 文件通过 P/Invoke 层进行相同的调用,如果对 LockFile 的调用返回 0,则引发异常。在您的情况下,您没有引发异常。如果文件被锁定,您将花费更少的时间,因为您没有处理堆栈展开。

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).

于 2009-03-30T18:30:12.567 回答
5

就我个人而言,我会在尝试打开它时捕获一个锁定的文件。如果它现在已解锁,则在您尝试打开它时可能会被锁定(即使只是几毫秒后)。

于 2009-03-30T18:29:41.803 回答
4

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.

于 2009-03-30T18:31:56.760 回答
1

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.

于 2009-05-15T08:14:15.397 回答
0

我认为没有尝试是不可能的,抓住。

于 2009-03-30T18:30:04.347 回答