Pipelines and buffer ownership
Pipelines and buffer ownership
A pipe transports bytes between a writer and a reader while managing reusable memory segments. Unlike a channel of typed messages, a pipe exposes a sequence of bytes that may contain several messages or only part of one. A delimiter or length prefix supplies framing. The reader receives a ReadOnlySequence<byte>, processes complete frames, and calls AdvanceTo(consumed, examined). Consumed means bytes may be reclaimed; examined means how far parsing looked. Never access a previously returned buffer after advancing or completing the reader. CancelPendingRead can make the current or next ReadAsync return IsCanceled without completing the pipe. A canceled result still requires an appropriate AdvanceTo before the next read; do not silently discard its bytes. Token-triggered cancellation can instead throw OperationCanceledException. These examples use the .NET 10 ASP.NET Core shared framework reference to make System.IO.Pipelines available without adding a separate NuGet package.
Baseline: .NET 10 / C# 14 (SDK candidate inherited, not installed). Each example is an independent project with predicted output. Build and runtime verification are pending. Run only a reviewed fixture in an approved disposable environment.
Read a short byte sequence
Writer completion signals that no additional bytes will arrive. This finite fixture stays far below pause thresholds, so writing before reading is safe here.
using System;using System.Buffers;using System.IO.Pipelines;using System.Text;var pipe = new Pipe();bool writerDone = false;try{ await pipe.Writer.WriteAsync("hello"u8.ToArray()); await pipe.Writer.CompleteAsync(); writerDone = true; var result = await pipe.Reader.ReadAsync(); try { Console.WriteLine(Encoding.UTF8.GetString(result.Buffer.ToArray())); } finally { pipe.Reader.AdvanceTo(result.Buffer.End); }}finally{ try { if (!writerDone) await pipe.Writer.CompleteAsync(); } finally { await pipe.Reader.CompleteAsync(); }}The copy returned by ToArray is independently owned. This convenient copy is not a zero-allocation parsing strategy.
Expected observation (reasoned, not executed):
helloKeep a partial frame across reads
The first read sees a complete buffer prefix but no newline. Mark nothing consumed, everything examined, then append the rest of the message.
using System;using System.Buffers;using System.IO.Pipelines;using System.Text;var pipe = new Pipe();bool writerDone = false;try{ await pipe.Writer.WriteAsync("ab"u8.ToArray()); var first = await pipe.Reader.ReadAsync(); try { Console.WriteLine(first.Buffer.PositionOf((byte)'\n') is null); } finally { pipe.Reader.AdvanceTo(first.Buffer.Start, first.Buffer.End); } await pipe.Writer.WriteAsync("c\n"u8.ToArray()); await pipe.Writer.CompleteAsync(); writerDone = true; var next = await pipe.Reader.ReadAsync(); var consumed = next.Buffer.Start; try { var end = next.Buffer.PositionOf((byte)'\n'); if (end is not { } delimiter) throw new FormatException("Missing delimiter"); Console.WriteLine(Encoding.UTF8.GetString(next.Buffer.Slice(0, delimiter).ToArray())); consumed = next.Buffer.GetPosition(1, delimiter); } finally { pipe.Reader.AdvanceTo(consumed, next.Buffer.End); }}finally{ try { if (!writerDone) await pipe.Writer.CompleteAsync(); } finally { await pipe.Reader.CompleteAsync(); }}The retained prefix joins the second write. GetPosition advances across the delimiter, not merely to it. Do not assume one segment per write.
Expected observation (reasoned, not executed):
TrueabcReject an unfinished frame at end of input
A completed pipe may still contain unread data. A finite input containing a missing final newline is invalid under this specific text protocol.
using System;using System.Buffers;using System.IO.Pipelines;var pipe = new Pipe();bool writerDone = false;try{ await pipe.Writer.WriteAsync("unfinished"u8.ToArray()); await pipe.Writer.CompleteAsync(); writerDone = true; var result = await pipe.Reader.ReadAsync(); try { bool invalid = result.IsCompleted && !result.Buffer.IsEmpty && result.Buffer.PositionOf((byte)'\n') is null; Console.WriteLine(invalid ? "truncated frame" : "continue parsing"); } finally { pipe.Reader.AdvanceTo(result.Buffer.End); }}finally{ try { if (!writerDone) await pipe.Writer.CompleteAsync(); } finally { await pipe.Reader.CompleteAsync(); }}Here the application rejects the whole input, so it deliberately discards all bytes. A production loop must process complete frames before rejecting a trailing incomplete frame.
Expected observation (reasoned, not executed):
truncated frameCommon mistakes and design limits
Advancing consumed to the end of an incomplete frame loses data. Setting examined to consumed after inspecting the entire partial buffer can cause immediate rereads and a busy loop. When processing only one of several frames, do not mark uninspected bytes examined; otherwise a subsequent read may wait unnecessarily. For a live protocol use a maximum frame size, coordinate writer/reader completion in finally blocks, run both concurrently, and handle canceled flush/read results. PauseWriterThreshold and ResumeWriterThreshold are pressure signals, not hard byte caps. An oversized incomplete frame can deadlock with a paused writer unless the parser rejects it or the protocol and thresholds are coordinated.
Apply the concept
For chunks "go" and "od\nnext", show the first consumed and examined offsets and the final retained bytes after extracting the first frame.
Check your work: First read: consumed 0, examined 2. Combined input is good\nnext. After parsing good, consumed 5. If next has also been inspected for a delimiter, examined 9; retain next (4 bytes).
Further study
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pipelines and buffer ownership — knowledge check
Apply the lesson concepts to the following scenarios.
What does AdvanceTo consumed identify?
A partial frame has no delimiter. What should the parser usually retain?
Does one pipe read equal one message?
What does IsCompleted on a read mean?
Why cap frame length?