Fix Utf8JsonWriter.Dispose{Async} after failed Stream Write{Async} (dotnet/corefx...
authorStephen Toub <stoub@microsoft.com>
Tue, 30 Jul 2019 02:35:49 +0000 (22:35 -0400)
committerGitHub <noreply@github.com>
Tue, 30 Jul 2019 02:35:49 +0000 (22:35 -0400)
commit34730b85df6e72565f19ecdc16781a8b5b15a993
tree5cb492b17711829190f1774d35b7b35128db58e9
parentd79ed020296a2ca784e818c48da0d3ba4eaf7151
Fix Utf8JsonWriter.Dispose{Async} after failed Stream Write{Async} (dotnet/corefx#39836)

* Fix Utf8JsonWriter.Dispose{Async} after failed Stream Write{Async}

By the time the `Utf8JsonWriter` writes to the underlying `Stream` as part of `Flush{Async}` it has already `Advance`'d the `_arrayBufferWriter`, but it hasn't reset `BytesPending` to 0.  If the write to the stream throws an exception then, we end up in an inconsistent state where `BytesPending` != 0 but there's no corresponding pending bytes to `Advance` the `_arrayBufferWriter`.  When we then `Dispose` the `Utf8JsonWriter`, we attempt to `Advance` the `_arrayBufferWriter` and fail.  Since `Utf8JsonWriter` will often be used in a `using` block, an exception from a `Write`/`Flush{Async}` call inside the `using` will then be masked as the `using`'s call to `Dispose` ends up failing and throwing a secondary exception.

* Address PR feedback

* Address PR feedback

Commit migrated from https://github.com/dotnet/corefx/commit/c38f2327e2d4e159acba06e23f38daed24661652
src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs
src/libraries/System.Text.Json/tests/Utf8JsonWriterTests.cs