diff --git a/src/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs b/src/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs index dd81627ab11f..3aa78de8c612 100644 --- a/src/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs +++ b/src/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs @@ -214,10 +214,10 @@ public override void Complete(Exception exception = null) _isCompleted = true; - _internalTokenSource?.Dispose(); - FlushInternal(); + _internalTokenSource?.Dispose(); + if (!_leaveOpen) { InnerStream.Dispose(); @@ -233,10 +233,10 @@ public override async ValueTask CompleteAsync(Exception exception = null) _isCompleted = true; - _internalTokenSource?.Dispose(); - await FlushAsyncInternal().ConfigureAwait(false); + _internalTokenSource?.Dispose(); + if (!_leaveOpen) { #if netcoreapp diff --git a/src/System.IO.Pipelines/tests/StreamPipeWriterTests.cs b/src/System.IO.Pipelines/tests/StreamPipeWriterTests.cs index e40d1899e1a8..80703cd38004 100644 --- a/src/System.IO.Pipelines/tests/StreamPipeWriterTests.cs +++ b/src/System.IO.Pipelines/tests/StreamPipeWriterTests.cs @@ -61,6 +61,25 @@ public async Task DataFlushedOnCompleteAsync() Assert.Equal("Hello World", Encoding.ASCII.GetString(stream.ToArray())); } + [Fact] + public async Task CompleteAsyncDoesNotThrowObjectDisposedException() + { + byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); + var stream = new MemoryStream(); + PipeWriter writer = PipeWriter.Create(stream, new StreamPipeWriterOptions(leaveOpen: true)); + + await writer.FlushAsync(); + bytes.AsSpan().CopyTo(writer.GetSpan(bytes.Length)); + writer.Advance(bytes.Length); + + Assert.Equal(0, stream.Length); + + await writer.CompleteAsync(); + + Assert.Equal(bytes.Length, stream.Length); + Assert.Equal("Hello World", Encoding.ASCII.GetString(stream.ToArray())); + } + [Fact] public async Task DataWrittenOnFlushAsync() {