From 9e5f09cb44e322849844fd3bbf757741429b1870 Mon Sep 17 00:00:00 2001 From: Justin Kotalik Date: Fri, 8 Feb 2019 08:44:34 -0800 Subject: [PATCH] Make Dispose not throw in StreamPipeWriter (#7376) --- src/Http/Http/src/StreamPipeWriter.cs | 34 ++++++++++++--------- src/Http/Http/test/StreamPipeWriterTests.cs | 19 ++++++++++++ 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/src/Http/Http/src/StreamPipeWriter.cs b/src/Http/Http/src/StreamPipeWriter.cs index 1cb545dcef..3c327d71d3 100644 --- a/src/Http/Http/src/StreamPipeWriter.cs +++ b/src/Http/Http/src/StreamPipeWriter.cs @@ -129,20 +129,7 @@ namespace System.IO.Pipelines return; } - _isCompleted = true; - - _internalTokenSource?.Dispose(); - - if (_completedSegments != null) - { - foreach (var segment in _completedSegments) - { - segment.Return(); - } - } - - _currentSegmentOwner?.Dispose(); - + Dispose(); // We still want to cleanup segments before throwing an exception. if (_bytesWritten > 0 && exception == null) { @@ -286,7 +273,24 @@ namespace System.IO.Pipelines public void Dispose() { - Complete(); + if (_isCompleted) + { + return; + } + + _isCompleted = true; + + _internalTokenSource?.Dispose(); + + if (_completedSegments != null) + { + foreach (var segment in _completedSegments) + { + segment.Return(); + } + } + + _currentSegmentOwner?.Dispose(); } /// diff --git a/src/Http/Http/test/StreamPipeWriterTests.cs b/src/Http/Http/test/StreamPipeWriterTests.cs index aaba3a6101..c2bfce4d1a 100644 --- a/src/Http/Http/test/StreamPipeWriterTests.cs +++ b/src/Http/Http/test/StreamPipeWriterTests.cs @@ -339,6 +339,25 @@ namespace System.IO.Pipelines.Tests Assert.Throws(() => Writer.GetSpan()); } + [Fact] + public void DisposeDoesNotThrowIfUnflushedData() + { + var streamPipeWriter = new StreamPipeWriter(new MemoryStream()); + streamPipeWriter.Write(new byte[1]); + + streamPipeWriter.Dispose(); + } + + [Fact] + public void CompleteAfterDisposeDoesNotThrowIfUnflushedData() + { + var streamPipeWriter = new StreamPipeWriter(new MemoryStream()); + streamPipeWriter.Write(new byte[1]); + + streamPipeWriter.Dispose(); + streamPipeWriter.Complete(); + } + [Fact] public void CallGetMemoryWithNegativeSizeHint_ThrowsArgException() {