- Quickly identify processes locking files with Handle and confirm patterns with ProcMon.
- Automate secure scripts: don't move files in use and manage MOTW with PowerShell.
- Differentiates between file and SQL Server locks and diagnoses the latter with DMV/XEvents.

When Windows displays the typical message that "the process cannot access the file because it is being used by another process ," the real problem isn't the file itself, but rather who has it open. Quickly identifying the culprit makes all the difference between a stable system and a string of production failures. This is where Handle, Process Monitor, and a few PowerShell tricks shine.
In this guide, we bring together pieces that are rarely explained together: how to hunt for file locks with Handle , how to confirm them with Process Monitor (ProcMon), how to prevent moving files in use from scripts, how to unblock the "Mark of the Web" with PowerShell, and also how to recognize different types of locks at the SQL Server level and diagnose their causes with DMV and Extended Events. We conclude with tools for debugging locks in web applications using DevTools Crash Analyzer.
What is a file lock in Windows and why does it happen?
A file lock occurs when a process maintains an open handle on a file , preventing another process from modifying or deleting it. The typical symptom is an access denied exception, especially in services that manipulate files quickly or concurrently.
A real-world example: On a Windows Server 2022 server, a custom service was failing with the error "Cannot open file XXX ." After instrumenting the machine with ProcMon, it was observed that just before the crash, MsSense.exe (Microsoft Defender for Endpoint) was accessing the file. Requesting an exclusion from Microsoft resolved the issue. Moral of the story: Sometimes the source is an EDR/antivirus program that inspects critical paths.
Other common scenarios include output folders from tools like HandBrake , where you want to move newly generated files; if you access them prematurely, the script will fail. In these situations, it's best to check if the file is still in use and wait for the process to release its handles. The important thing: never try to work on files while they are open.

Quickly locate the process locking a file with Handle (Sysinternals)
Handle is a Sysinternals utility that lists the file handles opened by processes . It's lightweight and straightforward, ideal when the error is intermittent and you need to confirm which process is blocking a specific path.
Recommended steps with Handle ( command line ): Download the Sysinternals suite (or just Handle), run the console as administrator, and use filters by filename or folder. If the lock disappears quickly, it's advisable to run the command in a loop (or schedule it) to avoid missing the critical moment.
Useful commands (syntax guide): Use "handle.exe -a path\to\file" to see who has that resource open; if you prefer to search by folder, filter by name partially; to identify specific PIDs, cross-reference with Task Manager . With user and detail options, you can refine the results, and if you locate the exact process (for example, MsSense.exe ), you can decide whether to apply an exclusion or change the workflow.
If the block isn't captured in time, combine Handle with scheduled scripts : run them every X seconds and log the output. Sometimes the block is very brief; recording the exact moment and the process involved is all you need to escalate to the responsible team or adjust the EDR configuration.
ProcMon, Resource Monitor and EDR Actual Pattern
Process Monitor offers an in-depth view of file system events (creation, reading, writing) with filters by path and process . Set up a filter for the suspected folder and record until the problem is reproduced; you'll see which binary touches the file, in what order, and with what result.
In the case mentioned, ProcMon showed that MsSense.exe was accessing the system just before the failure . Although a GPO exclusion existed, it didn't cover the specific flow. The solution was to request a tenant-level exclusion in Defender for Endpoint. Lesson: Exclusions must be applied at the correct point and cover the exact path or pattern.
As a quick alternative, the Resource Monitor (resmon.exe) lets you search for open handles by filename. This is useful if the file is still locked; if it disappears quickly, ProcMon or Handle with periodic sampling gives better results. Keep performance in mind: ProcMon can generate large data volumes ; use strict filters and stop capturing after replaying the event.
When services restart due to a crash, automate evidence collection: a script that triggers Handle/ProcMon upon system events (e.g., service error detection) will give you the name of the offending process without manual intervention.
Automate your workflow: Move files without touching them when they're in use
Suppose you have a HandBrake output folder and a script that moves files to their final destination every minute. You don't want to touch files that are still being written. There are several safe strategies:
- Check with Handle If there is a process with the file open; if there are active handles, the move is postponed. You can parse the output of "handle.exe" and act accordingly.
- Try to open the file with a Filestream in exclusive mode (no sharing); if it fails, it is in use and you should try again later.
- Check that the size stops growing for a reasonable interval; useful for transcoding streams.
- Detect that the producing process (HandBrake) no longer has active threads on that route, combining WMI and handler queries.
Practical tips: add an exponential backoff to retries to avoid saturating the disk; mark files "in transit" (e.g., by renaming them with a temporary extension) to avoid race conditions with other services; and log each decision (which files were skipped because they were in use) for later diagnostics.
If you need extra robustness, use a FileSystemWatcher that triggers checks when changes are complete, but remember that "Changed" can be triggered many times; the stable size/freed handle criterion is still key to getting the move right.
Unlock Mark of the Web with PowerShell
When you download files from the internet, Windows may mark the file with Mark of the Web (MOTW) . This isn't a process blocker, but it can prevent the file from running or opening normally. PowerShell fixes this with a single cmdlet.
For a specific file: run PowerShell as administrator and use `Unblock-File -Path "C:\path\file"` . This is immediate and useful when you trust the source. For folders with many files, use `Get-ChildItem "C:\path" | Unblock-File` and, if needed, filter by extension with `-Filter`.
Security recommendation: Only unblock files whose origin you are certain of . Scan them with antivirus software first. In corporate environments, it's advisable to automate unblocking in trusted repositories and maintain audit logs.
SQL Server Deadlocks: Concepts, Diagnosis, and Resolution
Database locks are not the same as file locks, but they often produce similar symptoms: waits that paralyze work . In SQL Server, locking is part of the engine to ensure consistency under concurrency. The problem arises when it persists for an extended period.
In SQL Server, each connection is a session identified by its session_id (SPID) . A single application can open multiple sessions, and one session can lock another. The duration of the lock depends on the query, the transaction, and the isolation level . SELECT statements lock only as long as necessary for reading unless the system is in a transaction; DML operations (INSERT/UPDATE/DELETE) hold locks for the duration of the query (and potentially the transaction).
When there is a serious impact, it is usually due to: 1) a session that holds resources for a long time and eventually releases them (degrading performance while it lasts), or 2) a session that never releases (remaining open during a transaction or trapped by application logic). In the first case, the situation changes quickly; in the second, the state is more stable and easier to isolate.
Recommended working method
The process is clear: 1) identify the root blocker , 2) locate the causing query/transaction, 3) understand the reason (plan/wait/open transaction), and 4) redesign the query and transaction . To capture evidence: DMVs (Dynamic Management Views/Functions) and Extended Events (XEvents) are your allies.
Essential DMVs for diagnosis
- sys.dm_exec_sessions y sys.dm_exec_requests: relate them to see who blocks whom by column blocking_session_id. Observe the status (running, executable, suspended, waiting), There waiting, and the last type of waiting.
- sys.dm_exec_input_buffer: shows you the last instruction sent by a session (for example, SELECT * FROM sys.dm_exec_input_buffer(66,0) for session_id 66).
- sys.dm_os_waiting_tasks: explains what wait_type is an active request.
- sys.dm_tran_locks: Lists the held locks; combine with waiting_tasks to see only what is currently waiting.
- sys.dm_tran_active_transactions y sys.dm_tran_session_transactions: contextualize open transactions (start, status, duration), useful for hunting orphan transactions.
In addition to ad-hoc queries, SSMS includes reports: on the server, Reports > Standard Reports > Activity: all locking transactions , and the Activity Monitor with the "Locked By" column. For long-term analysis, it captures periodic DMV results (PSSDiag/DiagManager are referenced for support).
Interpreting waiting and resource
The `wait_type` column indicates what the request is waiting for; `wait_time` helps you see if it progresses or jumps to another wait; and `wait_resource` tells you the specific resource (table, page, row, key). For example, `TAB:dbid:object_id:index_id` for table-level locks or `RID` for a specific row. Combining `hobt_id` with `sys.partitions` helps you locate an index or table.
When the open_transaction_count is greater than zero in the session or request, transactions are in progress, and therefore locks may persist beyond a specific statement. Also check reads, cpu_time, and memory_usage in the session to determine if a long query is active or if the SPID is waiting for client commands.
Extended Events and Blocking
To see the exact sequence of commands, create an XEvents session in SSMS. Events of interest include error/warning categories such as blocked_process_report , "attention," and "error_reported." Set the blocked process threshold with sp_configure (in seconds) so that reports are generated when a wait exceeds the threshold.
Typical blocking scenarios in SQL Server
- Normal query taking a long time and holding locks: optimize the plan, uses Query Store to detect suboptimal plans and, if necessary, offloads that OLTP workload to a reporting environment or read-only replication.
- SPID suspended with unconfirmed transaction After a timeout or cancellation: the batch ends, but the transaction remains open; check error control and use SET XACT_ABORT ON to self-revert upon errors.
- Client who does not consume all rows from a SELECT statement: Locks are held until the result set is read to the end; adjust your application to flush the cursor or paginate properly.
- Client/Server Distributed Deadlock: SQL Server cannot resolve it if the blockage is at the application layer (see examples A and B below).
- Session in state ROLL BACK: after canceling/deleting outside of the user's transaction or deadlock victim; you must wait for it to complete (with ADR in SQL 2019, the impact is reduced).
- Orphaned connection: the client dies and leaves open transactions; improves exception handling, considers XACT_ABORT and, if applicable, KILL of the SPID.
Distributed deadlocks at the application layer
Example A (a single thread on the client with two connections): The thread processes results from dbproc1 while SPID1 is blocked on a resource from SPID2; in turn, dbproc2 waits for the only thread that is busy, and the cycle closes. SQL Server cannot resolve this because only one of the resources belongs to it.
Example B (one thread per connection): dbproc2 (SELECT) produces rows and passes them to dbproc1, which attempts INSERT/UPDATE/DELETE, but that SPID is blocked by the first one. Again, a deadlock occurs between the application layer and the database. Solution: reasonable wait times , disciplined consumption of results, and coordination between threads.
When blocking is security: MOTW, warnings and best practices
In addition to process blocking, Windows may prevent downloaded files from opening with a security warning based on their source . Identify this warning in the file's Properties (using the "Unblock" option) or with PowerShell. Remember: not everything downloaded should be unblocked; if you have any doubts, scan the file with antivirus software first.
For large batches, automate with PowerShell and log what is unlocked and when. If your pipeline downloads artifacts from trusted sources, integrate Unblock-File into the post-download stage and apply compensating controls (signatures, hashes, etc.).
Diagnosing crashes and failures in web applications with DevTools Crash Analyzer
In the web world, a "block" is usually a front-end crash . Microsoft Edge includes the "Block Analyzer" tool in DevTools to demin and understand production stack traces. Key: annotate the trace with "Source Modules" (script URLs and byte-by-byte SHA-256 hashes of the content).
How to prepare your app: Install the @microsoft/edge-devtools-crash-analyzer-support library and invoke installErrorStackModuleAnnotations(Error) to append the "Source modules" section to the exceptions. This will allow DevTools to retrieve the appropriate source maps.
Make source maps accessible to DevTools. Ideally, publish them to the Azure Artifacts symbol server for on-demand retrieval. Using the comment `//# sourceMappingURL=` allows DevTools to cache them for future sessions. Note that `localhost` is not cached , so this workflow works best with actual production traces.
To open the tool: launch DevTools, use the Quick View menu or the Command Menu (Ctrl/Cmd+Shift+P), search for "Lock Analyzer," and paste the trace with "Source Modules." You'll be able to see original filenames and functions , load the source code in the Sources tab, and copy the entire demined stack if needed.
Good practices to reduce recurring crashes
- On servers with EDR/Defender, it applies precise exclusions to work routes and validate their effectiveness on the correct map (GPO vs. EDR tenant). Be sure to monitor before and after with ProcMon to confirm.
- In file orchestration scripts, don't force competition: detect active handles or stable size, use backoff and mark files in transit. Avoid operating during peak hours if volume is high.
- In SQL Server, shorten Transactions, lower the insulation level when appropriate, consume all customer rows, handle cancellations/errors, and trigger XACT_ABORT where needed. Query Store and XEvents should be part of everyday operations.
- In web applications, it instruments the capture of traces with source modules and publish source maps safely. This will shorten the diagnostic window.
With a combined approach—Handle to hunt processes with open files, ProcMon to map the system, PowerShell to automate and unlock MOTW, and SQL Server and DevTools for database and front-end locks—it is possible to isolate causes, reduce downtime, and prevent recurrences in Windows and mixed environments.
Table of Contents
- 1 What is a file lock in Windows and why does it happen?
- 2 Quickly locate the process locking a file with Handle (Sysinternals)
- 3 ProcMon, Resource Monitor and EDR Actual Pattern
- 4 Automate your workflow: Move files without touching them when they're in use
- 5 Unlock Mark of the Web with PowerShell
- 6 SQL Server Deadlocks: Concepts, Diagnosis, and Resolution
- 7 When blocking is security: MOTW, warnings and best practices
- 8 Diagnosing crashes and failures in web applications with DevTools Crash Analyzer
- 9 Good practices to reduce recurring crashes
