From c8d018df13b458963d9e21cab12d2fb6edd6f758 Mon Sep 17 00:00:00 2001 From: Justin Kotalik Date: Thu, 18 Jul 2019 16:16:57 -0700 Subject: [PATCH] Don't dispose StreamPipeWriter CancellationToken until after Flush --- .../System/IO/Pipelines/StreamPipeWriter.cs | 8 ++++---- .../tests/StreamPipeWriterTests.cs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) 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() {