Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

dotnet-io-pipelines

БесплатноБез исполняемых скриптовНе проверен

Building high-perf network I/O. PipeReader/PipeWriter, backpressure, protocol parsers, Kestrel.

wshaddixот wshaddix★ 94 звезды на GitHub

Об этом скилле

dotnet-io-pipelines

High-performance I/O patterns using System.IO.Pipelines. Covers PipeReader, PipeWriter, backpressure management, protocol parser implementation, and Kestrel integration. Pipelines solve the classic problems of buffer management, incomplete reads, and memory copying that plague traditional stream-based network code.

Out of scope: Async/await fundamentals and ValueTask patterns -- see [skill:dotnet-csharp-async-patterns]. Benchmarking methodology and Span<T> micro-optimization -- see [skill:dotnet-performance-patterns]. File-based I/O (FileStream, RandomAccess, MemoryMappedFile) -- see [skill:dotnet-file-io].

Cross-references: [skill:dotnet-csharp-async-patterns] for async patterns used in pipeline loops, [skill:dotnet-performance-patterns] for Span/Memory optimization techniques, [skill:dotnet-file-io] for file-based I/O patterns (FileStream, RandomAccess, MemoryMappedFile).


Why Pipelines Over Streams

Traditional Stream-based I/O forces developers to manage buffers manually, handle partial reads, and copy data between buffers. System.IO.Pipelines solves these problems:

Problem Stream Approach Pipeline Approach
Buffer management Allocate byte[], resize manually Automatic pooled buffer management
Partial reads Track position, concatenate fragments ReadResult with SequencePosition bookmarks
Backpressure None -- writer can outpace reader Built-in pause/resume thresholds
Memory copies Copy between buffers at each layer Zero-copy slicing with ReadOnlySequence<byte>
Lifetime management Manual byte[] lifecycle Pooled memory returned on AdvanceTo

The Pipe class connects a PipeWriter (producer) and a PipeReader (consumer) with an internal buffer pool, flow control, and completion signaling.


Core Concepts

Pipe, PipeReader, PipeWriter

// Create a pipe with default options (uses ArrayPool internally)
var pipe = new Pipe();

PipeWriter writer = pipe.Writer;  // Producer side
PipeReader reader = pipe.Reader;  // Consumer side

PipeWriter -- Producing Data

async Task FillPipeAsync(Stream source, PipeWriter writer,
    CancellationToken ct)
{
    const int minimumBufferSize = 512;

    while (true)
    {
        // Request a buffer from the pipe's memory pool
        Memory<byte> memory = writer.GetMemory(minimumBufferSize);

        int bytesRead = await source.ReadAsync(memory, ct);
        if (bytesRead == 0)
            break;  // End of stream

        // Tell the pipe how many bytes were written
        writer.Advance(bytesRead);

        // Flush makes data available to the reader.
        // FlushAsync may pause here if the reader is slow (backpressure).
        FlushResult result = await writer.FlushAsync(ct);
        if (result.IsCompleted)
            break;  // Reader stopped consuming
    }

    // Signal completion -- reader will see IsCompleted = true
    await writer.CompleteAsync();
}

Critical rules:

  • Call GetMemory or GetSpan before writing -- never write to a previously obtained buffer after Advance
  • Call Advance with the exact number of bytes written
  • Call FlushAsync to make data available to the reader and to respect backpressure

PipeReader -- Consuming Data

async Task ReadPipeAsync(PipeReader reader, CancellationToken ct)
{
    while (true)
    {
        ReadResult result = await reader.ReadAsync(ct);
        ReadOnlySequence<byte> buffer = result.Buffer;

        // Try to parse messages from the buffer
        while (TryParseMessage(ref buffer, out var message))
        {
            await ProcessMessageAsync(message, ct);
        }

        // Tell the pipe how much was consumed and how much was examined.
        // consumed: data that has been fully processed (will be freed)
        // examined: data that has been looked at (won't trigger re-read
        //           until new data arrives)
        reader.AdvanceTo(buffer.Start, buffer.End);

        if (result.IsCompleted)
            break;  // Writer finished and all data consumed
    }

    await reader.CompleteAsync();
}

Critical rules:

  • Always call AdvanceTo after ReadAsync -- failing to do so leaks memory
  • Pass both consumed and examined positions: consumed frees memory, examined prevents busy-wait when the buffer has been scanned but does not contain a complete message
  • Never access ReadResult.Buffer after calling AdvanceTo -- the memory may be recycled

Backpressure

Backpressure prevents fast producers from overwhelming slow consumers. The pipe pauses the writer when unread data exceeds a threshold.

PipeOptions Configuration

var pipe = new Pipe(new PipeOptions(
    pauseWriterThreshold: 64 * 1024,   // Pause writer at 64 KB buffered
    resumeWriterThreshold: 32 * 1024,  // Resume writer when buffer drops to 32 KB
    minimumSegmentSize: 409
Полный SKILL.md на GitHub

Установить dotnet-io-pipelines в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл dotnet-io-pipelines?

Building high-perf network I/O. PipeReader/PipeWriter, backpressure, protocol parsers, Kestrel.

Как установить скилл dotnet-io-pipelines?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл dotnet-io-pipelines запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить dotnet-io-pipelines с