Skip to content

MessagePack for C# v4: Round5 - #2291

Draft
neuecc wants to merge 6 commits into
masterfrom
v4
Draft

MessagePack for C# v4: Round5#2291
neuecc wants to merge 6 commits into
masterfrom
v4

Conversation

@neuecc

@neuecc neuecc commented Aug 14, 2026

Copy link
Copy Markdown
Member

This round finalizes the approach for async deserialization.

Async deserialization uses a two-pass design:
the first pass scans for message boundaries, and the second pass synchronously deserializes the now-bounded buffer.

True async, meaning a design that checks for and awaits buffer refills in the middle of decoding a value, costs too much performance.
Even granting that .NET 11's async runtime may improve things somewhat.

Adding complex code to compensate for that degradation, such as buffer-size checks or bouncing between async and sync paths, is wasted effort.
Grabbing a buffer and processing it synchronously in one go is the foundation of performance,
and serializers are inherently suited to working that way: message boundaries form well-defined blocks, and a single block is never extremely large.

Since skipping is much lighter than actually reading, the performance concern about being two-pass mostly doesn't materialize.
It is certainly better than true async.

PipeReader's (consumed, examined) model is a natural fit for this kind of processing.
By delegating all the complex buffer management to PipeReader, the scanner that actually finds message boundaries ends up being a small amount of code.

Additionally, when the reader is IsCompleted, the two-pass flow is skipped entirely and the data is deserialized synchronously right away.
This eliminates the overhead in typical situations such as a fully received request body in ASP.NET.

The final API looks like this:

Task<T> DeserializeAsync<T>(PipeReader pipeReader, MessagePackSerializerOptions options, CancellationToken cancellationToken = default)
IAsyncEnumerable<T> DeserializeMessagesAsync<T>(PipeReader pipeReader, MessagePackSerializerOptions options, CancellationToken cancellationToken = default)
IAsyncEnumerable<T> DeserializeElementsAsync<T>(PipeReader pipeReader, MessagePackSerializerOptions options, CancellationToken cancellationToken = default)

DeserializeMessagesAsync streams a sequence of concatenated messages, JSONL-style.
DeserializeElementsAsync streams the elements of a MessagePack array.
These correspond to DeserializeAsyncEnumerable(bool topLevelValues) in System.Text.Json.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant