0.1.0 · released · .NET 10Read Markdown ↗

Replicate writes to multiple writable streams

TeeForge 0.1.0 · .NET 10 · released

Use a write-only wrapper and explicitly retain destination ownership.

Run from the repository root:

dotnet run --project samples/TeeForge.Quickstart -c Release -- replicate

The runner calls this example's RunAsync method with a cancellation token. The example checks its result and throws on failure. Source: samples/TeeForge.Quickstart/ReplicationExample.cs.

using TeeForge.Mirroring;

namespace TeeForge.Quickstart;

internal static class ReplicationExample
{
    public static async Task RunAsync(CancellationToken cancellationToken)
    {
        byte[] payload = "Replicate writes to multiple writable streams."u8.ToArray();
        await using var first = new MemoryStream();
        await using var second = new MemoryStream();

        // ReplicaStream needs only writable destinations; it does not expose reads or seeking.
        await using (var replicas = new ReplicaStream(
            [first, second], new ReplicaStreamOptions(leaveOpen: true)))
        {
            await replicas.WriteAsync(payload, cancellationToken);
            await replicas.FlushAsync(cancellationToken);
        }

        if (!first.CanWrite || !second.CanWrite ||
            !first.ToArray().AsSpan().SequenceEqual(payload) ||
            !second.ToArray().AsSpan().SequenceEqual(payload))
        {
            throw new InvalidOperationException("Both replicas must receive the payload and remain open.");
        }
    }
}

Usage guide · All recipes