Locking a region of a file gives the threads of the locking process exclusive access to the specified region using this file handle. If the file handle is inherited by a process created by the locking process, the child process is not granted access to the locked region. If the locking process opens the file a second time, it cannot access the specified region through this second handle until it unlocks the region.

Locking a region of a file does not prevent reading from a mapped file view.

You can lock bytes that are beyond the end of the current file. This is useful to coordinate adding records to the end of a file.

Exclusive locks cannot overlap an existing locked region of a file. For more information, see LockFileEx.

If
LockFile cannot lock a region of a file, it returns zero immediately. It does not block. To issue a file lock request that will block until the lock is acquired, use
LockFileEx without the LOCKFILE_FAIL_IMMEDIATELY flag.

If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the locks are unlocked by the operating system. However, the time it takes for the operating system to unlock these locks depends upon available system resources. Therefore, it is recommended that your process explicitly unlock all files it has locked when it terminates. If this is not done, access to these files may be denied if the operating system has not yet unlocked them.

In Windows 8 and Windows Server 2012, this function is supported by the following technologies.