Skip to content

Close the redirected streams used by Process.ReadAll* and RunAndCaptureText on Dispose - #137657

Merged
adamsitnik merged 3 commits into
dotnet:mainfrom
adamsitnik:process-runandcapture-dispose-streams
Nov 17, 2026
Merged

adamsitnik merged 3 commits into
dotnet:mainfrom
adamsitnik:process-runandcapture-dispose-streams

Conversation

@adamsitnik

@adamsitnik adamsitnik commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Process.Dispose closes the redirected standard output and error only when the caller can't have a reference to them. It used to decide that by the read mode of each stream. ReadAllText, ReadAllBytes and ReadAllLines (and their Async versions) put the streams into the same synchronous mode as the StandardOutput/StandardError getters. So their streams were never closed by Dispose, although the caller never got a reference to them.

This affects every Process that uses these APIs, and also Process.RunAndCaptureText/RunAndCaptureTextAsync, which call ReadAllText(Async) on a Process they never expose. Their pipes stayed open until the GC finalized them. On Windows, before #137507, that was never. A user reported the growth in #137501 (comment).

Fix

Process now tracks whether the caller obtained each stream from the StandardOutput/StandardError getters, in the same way it already does for StandardInput (_standardInputAccessed). Dispose closes every stream that the caller didn't obtain:

Stream usage Before After
Not used closed closed
BeginOutputReadLine/BeginErrorReadLine closed closed
StandardOutput/StandardError getter left to the caller left to the caller
ReadAll* without the getter left open closed

Because Dispose can now close the streams used by ReadAllLines, the Windows ReadAllLines iterator now holds references to both pipe handles until the enumeration ends (DangerousAddRef/DangerousRelease), as the Unix iterator and ReadAllText/ReadAllBytes already did. Without that, disposing the Process during the enumeration would close a handle with an overlapped read still pending, and the iterator's cleanup would throw ObjectDisposedException before freeing its resources.

Testing

  • The full System.Diagnostics.Process.Tests suite passes on Windows x64 (Release), except ChildProcess_CanBreakAwayFromJob, which also fails without this change in my environment.
  • The following test was used to verify the fix, but it isn't part of this PR because it's flaky: any handle or file descriptor that the runtime opens during the measurement (for example for EventPipe or the GC) changes the count.
    • Without the fix it failed consistently, with exactly 2 leaked handles per call (+20).
    • With the fix it passed.
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[PlatformSpecific(TestPlatforms.Windows | TestPlatforms.Linux)] // HandleCount is not supported on other platforms
[InlineData(false)]
[InlineData(true)]
public void RunAndCaptureText_ClosesRedirectedStreams(bool useAsync)
{
    // The handles are counted in a separate process, so other tests don't affect the count.
    RemoteExecutor.Invoke(async (string useAsyncArg) =>
    {
        bool useAsync = bool.Parse(useAsyncArg);
        const int Iterations = 10;

        using Process template = CreateProcess(static () =>
        {
            Console.Write("out");
            Console.Error.Write("err");
            return RemoteExecutor.SuccessExitCode;
        });

        template.StartInfo.RedirectStandardOutput = true;
        template.StartInfo.RedirectStandardError = true;

        await RunAndCaptureTextAsync(); // warm up
        int handleCountBefore = GetHandleCount();

        for (int i = 0; i < Iterations; i++)
        {
            await RunAndCaptureTextAsync();
        }

        // Without disposing the redirected streams, every iteration would leak two handles.
        Assert.InRange(GetHandleCount() - handleCountBefore, int.MinValue, Iterations - 1);

        async Task RunAndCaptureTextAsync()
        {
            ProcessTextOutput result = useAsync
                ? await Process.RunAndCaptureTextAsync(template.StartInfo)
                : Process.RunAndCaptureText(template.StartInfo);

            Assert.Equal("out", result.StandardOutput);
            Assert.Equal("err", result.StandardError);
        }

        static int GetHandleCount()
        {
            using Process currentProcess = Process.GetCurrentProcess();
            return currentProcess.HandleCount;
        }
    }, useAsync.ToString()).Dispose();
}

Note

This PR description was generated with the help of GitHub Copilot.

The ReadAll* methods, and the RunAndCaptureText(Async) methods built on top
of them, put the redirected standard output and error into synchronous read
mode, so Process.Dispose left them open for the caller although the caller
never obtained them. Track whether the streams were obtained from the
StandardOutput/StandardError getters instead, like for StandardInput.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

Process.Dispose now closes the streams used by ReadAllLines, so the Windows
iterator must hold references to the handles across yields, like the Unix
one. Otherwise, disposing the Process during the enumeration closes a handle
with a pending overlapped read, and the cleanup in the iterator's finally
block throws before freeing its resources.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: 8cfdacb8-9380-470b-83d0-2598d9255b9b
@adamsitnik

Copy link
Copy Markdown
Member Author

Process.Dispose closes the redirected standard output and error only when the caller can't have a reference to them.

@jkotas I will later update the Process SKILL to ensure such bugs are discovered as well

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Deterministic regression tests are missing for stream disposal across the sync/async ReadAll variants and Windows iterator cleanup when disposal occurs with a pipe read pending.

1 open issue
What changed in this PR

This PR fixes redirected-stream cleanup in System.Diagnostics.Process for ReadAll* and RunAndCaptureText, while preserving caller ownership of readers obtained through the public getters.

Changes:

  • Track whether callers obtained standard output and error readers, and close unexposed readers during disposal.
  • Keep Windows pipe handles alive across ReadAllLines yields until iterator cleanup completes.
File Description
src/​libraries/​System.Diagnostics.Process/​src/​System/​Diagnostics/​Process.Multiplexing.Windows.cs Retains and releases pipe handles around line enumeration.
src/​libraries/​System.Diagnostics.Process/​src/​System/​Diagnostics/​Process.cs Tracks reader ownership to close internally consumed streams.

Review effort: Balanced

…re-dispose-streams

# Conflicts:
#	src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Multiplexing.Windows.cs
@adamsitnik
adamsitnik enabled auto-merge (squash) November 17, 2026 09:11
@adamsitnik
adamsitnik requested a review from krwq November 17, 2026 09:30

@krwq krwq left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@adamsitnik

Copy link
Copy Markdown
Member Author

/ba-g the failure is unrelated

Details
  System.TestStructs -> /Users/runner/work/1/s/artifacts/bin/System.TestStructs/Release/netstandard2.0/System.TestStructs.dll
  Generating native code
  Generating native code
  Generating native code
  Fatal error.
  System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
     at System.Collections.Generic.ObjectEqualityComparer`1[[System.__Canon, System.Private.CoreLib, Version=12.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].GetHashCode(System.__Canon)
     at System.Collections.Generic.Dictionary`2[[System.__Canon, System.Private.CoreLib, Version=12.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[Internal.Text.Utf8String, ILCompiler.Compiler, Version=12.0.0.0, Culture=neutral, PublicKeyToken=null]].FindValue(System.__Canon)
     at ILCompiler.ObjectWriter.ObjectWriter.GetMangledName(ILCompiler.DependencyAnalysis.ISymbolNode)
     at ILCompiler.ObjectWriter.ObjectWriter.EmitObject(System.IO.Stream, System.Collections.Generic.IReadOnlyCollection`1<ILCompiler.DependencyAnalysisFramework.DependencyNode>, ILCompiler.DependencyAnalysis.IObjectDumper, ILCompiler.Logger)
     at ILCompiler.ObjectWriter.ObjectWriter.EmitObject(System.String, System.Collections.Generic.IReadOnlyCollection`1<ILCompiler.DependencyAnalysisFramework.DependencyNode>, ILCompiler.DependencyAnalysis.NodeFactory, ILCompiler.ObjectWriter.ObjectWritingOptions, ILCompiler.DependencyAnalysis.IObjectDumper, ILCompiler.Logger)
     at ILCompiler.Compilation.ILCompiler.ICompilation.Compile(System.String, ILCompiler.ObjectDumper)
     at ILCompiler.Program.Run()
     at ILCompiler.ILCompilerRootCommand+<>c__DisplayClass266_0.<.ctor>b__0(System.CommandLine.ParseResult)
     at System.CommandLine.Invocation.InvocationPipeline.Invoke(System.CommandLine.ParseResult)
     at ILCompiler.Program.Main(System.String[])

@adamsitnik
adamsitnik disabled auto-merge November 17, 2026 12:47
@adamsitnik
adamsitnik merged commit 383fdc5 into dotnet:main Nov 17, 2026
66 of 69 checks passed
@adamsitnik

Copy link
Copy Markdown
Member Author

/backport to release/11.0

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0 (link to workflow run)

@jkotas

jkotas commented Nov 17, 2026

Copy link
Copy Markdown
Member

/ba-g the failure is unrelated

File a known issue on this? https://github.com/dotnet/runtime/blob/main/docs/workflow/ci/failure-analysis.md#what-to-do-if-you-determine-the-failure-is-unrelated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants