Question

Is there a way, through .Net or by dropping to the Win32 API in .Net, to access the Windows global file lock table?

I'm looking for a better solution to determining if a group of files are locked other than checking each individual file to see if a lock has been taken on it.

Was it helpful?

Solution

No, it is stored in ring 0 code. Kernel code, only a device driver can get to it. The kind that dynamically gets installed by, for example, SysInternals' Handle utility. Whose author also reverse-engineered the undocumented kernel structures to find that table and is willing to maintain that code for all previous and future Windows versions. Hopefully.

This is quite intentionally out of reach from user-mode code. Nothing ever good happens when programs try to get that kind of information. Like your plan, checking if a file is locked. That simply cannot work reliably on a multitasking operating system.

Suppose that would work and you'd write an IsLocked() function. You'll return false when you find out that file(s) are not locked. To be pre-empted by an operating system context switch that interrupts your thread just as IsLocked() is returning to the caller. And yielding to another thread in another process that locks the file. When your thread resumes, the caller gets false but the file is locked anyway. Total fail whale. Such a bug is enormously difficult to troubleshoot. It will happen, just not nearly frequently enough to have a shot at discovering why it doesn't work.

Locks have to be atomic, absolutely essential for them to work correctly. In other words, a test-and-set operation must be un-interruptable. Which is very easy to do in Windows, just open the file. If you can't acquire the lock then that will fail. If it doesn't then nobody else can open it because you also acquired the lock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top