dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.21k stars 4.72k forks source link

`process.MainModule` throws `Win32Exception` instead of `InvalidOperationException` when process has exited in some cases #105090

Open MichalPetryka opened 3 months ago

MichalPetryka commented 3 months ago

Description

Accessing MainModule after process exit throws an exception that doesn't match the documentation. The code should either be changed to detect that case or the docs should be changed.

Reproduction Steps

using Process process = Process.GetProcessById(someId);
_ = process.Handle;
process.WaitForExit();
Console.WriteLine(process.ExitCode);
Console.WriteLine(process.MainModule?.FileName ?? "null");

Expected behavior

Throws InvalidOperationException as per docs.

Actual behavior

Throws:

Unhandled exception. System.ComponentModel.Win32Exception (299): Only part of a ReadProcessMemory or WriteProcessMemory request was completed.
   at System.Diagnostics.NtProcessManager.EnumProcessModulesUntilSuccess(SafeProcessHandle, IntPtr[], Int32, Int32&, Int32) + 0x91
   at System.Diagnostics.NtProcessManager.GetModules(Int32, Boolean) + 0x110
   at System.Diagnostics.NtProcessManager.GetFirstModule(Int32) + 0xf

Regression?

Not sure.

Known Workarounds

No response

Configuration

Windows 10.0.19045 X64 .NET 9

Other information

No response

dotnet-policy-service[bot] commented 3 months ago

Tagging subscribers to this area: @dotnet/area-system-diagnostics-process See info in area-owners.md if you want to be subscribed.

tannergooding commented 3 months ago

The docs here should likely be changed to just say something like Win32Exception: An error occurred during the native system call to query process information

There is no way to document all potential cases that native errors for and those can expand over time based on changes that are outside the control of .NET

adamsitnik commented 3 months ago

I agree with @tannergooding , we should update the docs.