dotnet / dotnet/aspnetcore

ReusableUtf8JsonWriter holds on the `IBufferWriter<byte>` after `Return`

Open
#62,263 1 comment 0 reactions 0 assignees View on GitHub
area-signalr
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

https://github.com/dotnet/aspnetcore/blob/6a96694cda568cc8ebec2a0b34e408842eb9805f/src/SignalR/common/Shared/ReusableUtf8JsonWriter.cs#L59

With `Reset` only the [internal state is reset](https://github.com/dotnet/runtime/blob/f29cccfec070182f8b59791881d1057293d90a1d/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs#L362-L377), but the output remains the same (cf. [code](https://github.com/dotnet/runtime/blob/f29cccfec070182f8b59791881d1057293d90a1d/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs#L263-L279)).

So the `IBufferWriter` that is set in `Rent` will be referenced by the (pooled) Utf8JsonWriter, so the lifetime for the `IBufferWriter` is bound to the pooled Utf8JsonWriter -- at least until the next `Rent` when a new one is set. Thus the `IBufferWriter` can't be GCed.

In the STJ internal type `Utf8JsonWriterCache` an [internal method is used to reset the output too](https://github.com/dotnet/runtime/blob/624737eb3796e1a760465912b27ac349965d8ba5/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriterCache.cs#L81).

I'm just curios if the extended lifetime is a latent problem or not.

Possible mitigations could be:
* `Dispose` -- not really, as the instance can't be re-used then
* `Reset(Stream.Null)` -- solves the lifetime problem, but [allocates](https://github.com/dotnet/runtime/blob/f29cccfec070182f8b59791881d1057293d90a1d/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs#L304-L308)
* reset by setting to a null-IBufferWriter (type needs to be created)
* ?
* make `Utf8JsonWriter.ResetAllStateForCacheReuse` `public` -- but this doesn't play nice with the disposal checks in that type

https://github.com/dotnet/aspnetcore/pull/9607 introduced the `ReusableUtf8JsonWriter`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.