Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 1d83d60

Browse files
lzybkrstephentoub
authored andcommitted
Speed up Windows ProcessManager.OpenProcess (#25478)
If a process is running as a normal user (not elevated), many calls to `kernel32.OpenProcess` fail. In `ProcessManager.OpenProcess`, when the first call to `kernel32.OpenProcess` fails, another call is made indirectly in `ProcessManager.IsProcessRunning` which will also fail. When `ProcessManager.IsProcessRunning` can't get a handle to the process, it falls back on a much more expensive check - enumerating all processes. The fix is to assume the process is running if the error code is ERROR_ACCESS_DENIED. This performance issue adds roughly 1 second of overhead when running `Get-Process` in an interactive non-elevated PowerShell session where the CPU property is displayed.
1 parent d61b609 commit 1d83d60

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,8 @@ public static SafeProcessHandle OpenProcess(int processId, int access, bool thro
195195
}
196196

197197
// If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true.
198-
if (!IsProcessRunning(processId))
198+
// Assume the process is still running if the error was ERROR_ACCESS_DENIED for better performance
199+
if (result != Interop.Errors.ERROR_ACCESS_DENIED && !IsProcessRunning(processId))
199200
{
200201
if (throwIfExited)
201202
{

0 commit comments

Comments
 (0)