Hands-on journey · .NET 8+

Learn CoAkka Runtime with C#/.NET

Install the exact NuGet package, use await using for lifecycle and learn Embedded first. Advanced keeps the target stable while moving its handler to a peer, then opens File Lane, Stream Lane and effective Monitor facts.

Beginner · 01 / 04

Create a project and receive a reply

Use .NET SDK 8 or later. The project pins CoAkka.Runtime 3.3.2; NuGet selects the native RID asset for the host.

Check .NET
dotnet --version
Create the folder
mkdir coakka-csharp-demo
cd coakka-csharp-demo
CoAkkaPortal.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
    <SampleFile Condition="'$(SampleFile)' == ''">FirstRun</SampleFile>
    <StartupObject>CoAkkaPortal.$(SampleFile)</StartupObject>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="$(SampleFile).cs" />
    <PackageReference Include="CoAkka.Runtime" Version="3.3.2" />
  </ItemGroup>
</Project>
FirstRun.cs
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class FirstRun
{
    public static async Task Main()
    {
        const string target = "customers.accept";
        await using var runtime = RuntimeHost.StartLocal(
            systemName: "customer-app",
            target: target,
            nodeId: "customer-app-1");

        runtime.RegisterTextHandler(target, name => $"accepted-{name}");
        var reply = await runtime.AskTextAsync(
            source: "customer-api",
            target: target,
            payload: "hello",
            timeoutMs: 2_000);
        Console.WriteLine(reply);
    }
}
Terminal
dotnet run -p:SampleFile=FirstRun

Expected result

accepted-hello
StartLocal
Creates an Embedded owner and local route for one target.
RegisterTextHandler
A short UTF-8 handler; Core still owns delivery and outcomes.
AskTextAsync
The .NET async projection of request/reply.
await using
Seals admission and waits for shutdown without discarding close failure.
SampleFile
The project compiles only the selected lesson source, so every episode has an independent entry point.

Inspect NuGet 3.3.2 (optional)

Beginner · 02 / 04

Name the work

Create Quote.cs beside the project. The caller uses orders.quote without knowing handler placement.

Quote.cs
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class Quote
{
    public static async Task Main()
    {
        const string target = "orders.quote";
        await using var runtime = RuntimeHost.StartLocal(
            systemName: "orders",
            target: target,
            nodeId: "orders-csharp-1");

        runtime.RegisterTextHandler(target, quantity =>
            (int.Parse(quantity) * 120_000).ToString());
        foreach (var quantity in new[] { 1, 2 })
        {
            var reply = await runtime.AskTextAsync(
                source: "checkout",
                target: target,
                payload: quantity.ToString(),
                timeoutMs: 2_000);
            Console.WriteLine($"quantity={quantity} quote={reply} VND");
        }
    }
}
Terminal
dotnet run -p:SampleFile=Quote

Expected result

quantity=1 quote=120000 VND
quantity=2 quote=240000 VND

Beginner · 03 / 04

Read DeadletterException

ReasonCode preserves Core's stable numeric code; Reason is its exact short name. Never classify exception text.

RouteMiss.cs
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class RouteMiss
{
    public static async Task Main()
    {
        await using var runtime = RuntimeHost.StartLocal(
            systemName: "orders",
            target: "orders.quote",
            nodeId: "orders-csharp-1");

        try
        {
            await runtime.AskTextAsync(
                source: "checkout",
                target: "orders.missing",
                payload: "1",
                timeoutMs: 2_000);
        }
        catch (DeadletterException error)
        {
            Console.WriteLine(
                $"deadletter reason={error.Deadletter.ReasonCode} " +
                $"target={error.Deadletter.OriginalEnvelope.Target}");
        }
    }
}
Terminal
dotnet run -p:SampleFile=RouteMiss

Expected result

deadletter reason=2 target=orders.missing

Read shared delivery outcomes.

Beginner · 04 / 04

Let the app own RuntimeHost

Register the host in the app composition root/DI scope, pass it to business code and dispose it during app shutdown.

Integration.cs
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class Integration
{
    private static async Task RunCheckout(RuntimeHost runtime)
    {
        var reply = await runtime.AskTextAsync(
            source: "checkout",
            target: "orders.quote",
            payload: "2",
            timeoutMs: 2_000);
        Console.WriteLine($"checkout total={reply} VND");
    }

    public static async Task Main()
    {
        const string target = "orders.quote";
        await using var runtime = RuntimeHost.StartLocal(
            systemName: "orders",
            target: target,
            nodeId: "orders-csharp-1");
        runtime.RegisterTextHandler(target, quantity =>
            (int.Parse(quantity) * 120_000).ToString());
        await RunCheckout(runtime);
    }
}
Terminal
dotnet run -p:SampleFile=Integration

Expected result

checkout total=240000 VND

Advanced · 05 / 08

Move the handler to a peer

Create two files and open two terminals. The target stays stable. NETWORK_NODE listens; the caller is OUTBOUND_ONLY.

QuoteService.cs
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class QuoteService
{
    public static async Task Main()
    {
        const string target = "orders.quote";
        var startSpec = new ConnectorStartSpec(
            SystemName: "orders",
            NodeId: "quote-csharp-1",
            Routes: [RuntimeHost.LocalRoute(target)],
            Network: RuntimeNetworkConfig.NetworkNode(
                bindHost: "127.0.0.1",
                bindPort: 19_322,
                advertiseHost: "127.0.0.1",
                advertisePort: 19_322));

        await using var runtime = RuntimeHost.Start(startSpec);
        runtime.RegisterTextHandler(target, quantity =>
            (int.Parse(quantity) * 120_000).ToString());
        Console.WriteLine("quote service ready on 127.0.0.1:19322");
        Console.WriteLine("Press Enter to stop...");
        Console.ReadLine();
    }
}
Terminal 1
dotnet run -p:SampleFile=QuoteService
Checkout.cs
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class Checkout
{
    public static async Task Main()
    {
        const string target = "orders.quote";
        var route = new RuntimeRouteSpec(
            Target: target,
            Endpoints:
            [
                new RuntimeEndpointSpec(
                    Host: "127.0.0.1",
                    Port: 19_322,
                    Weight: 1)
            ],
            Strategy: RuntimeRouteStrategy.SingleOwner);
        var startSpec = new ConnectorStartSpec(
            SystemName: "orders",
            NodeId: "checkout-csharp-1",
            Routes: [route],
            Network: RuntimeNetworkConfig.OutboundOnly());

        await using var runtime = RuntimeHost.Start(startSpec);
        var reply = await runtime.AskTextAsync(
            source: "checkout",
            target: target,
            payload: "3",
            timeoutMs: 2_000);
        Console.WriteLine($"order quote: {reply} VND");
    }
}
Terminal 2
dotnet run -p:SampleFile=Checkout

Expected result

order quote: 360000 VND
NetworkNode
Bind/advertise are explicit; production uses a reachable private address.
RuntimeRouteSpec
Holds target, endpoints and strategy.
SingleOwner
One owner here; multi-endpoint/failover opens in the shared reference.

Read distributed, failover and retry.

Advanced · 06 / 08

File Lane with an exact-owner grant

Do not run blocking waits on a UI thread. SEND and RECEIVE must both be Succeeded before forget/dispose.

FileLaneDemo.cs
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class FileLaneDemo
{
    private static FileTransferSnapshot WaitTerminal(
        FileLane lane,
        string transferId,
        FileTransferDirection direction)
    {
        ulong sequence = 0;
        while (true)
        {
            var snapshot = lane.WaitTransfer(
                transferId: transferId,
                direction: direction,
                afterUpdateSequence: sequence,
                timeoutMs: 5_000);
            if (snapshot.Terminal) return snapshot;
            sequence = snapshot.UpdateSequence;
        }
    }

    public static void Main()
    {
        var directory = Path.Combine(Path.GetTempPath(), $"coakka-csharp-{Guid.NewGuid():N}");
        Directory.CreateDirectory(directory);
        try
        {
            var source = Path.Combine(directory, "source.txt");
            var destination = Path.Combine(directory, "received.txt");
            File.WriteAllText(source, "hello from File Lane");
            var digest = FileLane.Sha256(source);

            using var receiver = FileLane.OpenOwned(
                config: new FileLaneConfig(),
                owner: new LaneOwnerConfig(
                    OwnerInstanceId: "receiver-csharp-1",
                    AdvertisedHost: "127.0.0.1"));
            using var sender = FileLane.Open();
            const string transferId = "csharp-file-1";
            var grant = receiver.PrepareReceiveGrant(
                new FileReceiveSpec(
                    TransferId: transferId,
                    AuthorizationToken: "file-token-1",
                    DestinationPath: destination,
                    ExpectedSize: digest.Size,
                    ExpectedSha256: digest.Sha256));
            sender.SubmitSend(grant.ToSendSpec(sourcePath: source, timeoutMs: 5_000));

            var sent = WaitTerminal(sender, transferId, FileTransferDirection.Send);
            var received = WaitTerminal(receiver, transferId, FileTransferDirection.Receive);
            if (!sent.Succeeded || !received.Succeeded)
                throw new InvalidOperationException("File Lane did not complete on both peers");
            Console.WriteLine(File.ReadAllText(destination));
            sender.Forget(transferId, FileTransferDirection.Send);
            receiver.Forget(transferId, FileTransferDirection.Receive);
        }
        finally
        {
            Directory.Delete(directory, recursive: true);
        }
    }
}
Terminal
dotnet run -p:SampleFile=FileLaneDemo

Expected result

hello from File Lane

Read the File Lane contract.

Advanced · 07 / 08

Stream Lane with borrowed Span

Span<byte>/ReadOnlySpan<byte> is valid only during the callback. The example copies a frame into a string before retaining it.

StreamLaneDemo.cs
using System.Text;
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class StreamLaneDemo
{
    private static StreamSessionSnapshot WaitTerminal(
        StreamLane lane,
        string sessionId,
        StreamDirection direction)
    {
        ulong sequence = 0;
        while (true)
        {
            var snapshot = lane.WaitSession(
                sessionId: sessionId,
                direction: direction,
                afterUpdateSequence: sequence,
                timeoutMs: 5_000);
            if (snapshot.Terminal) return snapshot;
            sequence = snapshot.UpdateSequence;
        }
    }

    public static void Main()
    {
        var frames = new Queue<byte[]>(
            new[] { Encoding.UTF8.GetBytes("frame-one"), Encoding.UTF8.GetBytes("frame-two") });
        var received = new List<string>();

        using var publisher = StreamLane.OpenOwned(
            config: new StreamLaneConfig(),
            owner: new LaneOwnerConfig(
                OwnerInstanceId: "publisher-csharp-1",
                AdvertisedHost: "127.0.0.1"));
        using var subscriber = StreamLane.Open();
        const string sessionId = "csharp-stream-1";
        var grant = publisher.PreparePublishGrant(
            new StreamPublishSpec(
                SessionId: sessionId,
                AuthorizationToken: "stream-token-1",
                FormatId: 1,
                MaxFrameBytes: 1_024,
                Source: destination =>
                {
                    if (frames.Count == 0) return StreamSourceResult.End;
                    var frame = frames.Dequeue();
                    frame.CopyTo(destination);
                    return StreamSourceResult.Frame(frame.Length);
                }));
        subscriber.Subscribe(
            grant.ToSubscribeSpec(
                initialWindowBytes: 4_096,
                consumer: (data, _) =>
                {
                    received.Add(Encoding.UTF8.GetString(data));
                    return StreamConsumerDecision.Continue;
                },
                timeoutMs: 5_000));

        var published = WaitTerminal(publisher, sessionId, StreamDirection.Publish);
        var subscribed = WaitTerminal(subscriber, sessionId, StreamDirection.Subscribe);
        if (!published.Succeeded || !subscribed.Succeeded)
            throw new InvalidOperationException("Stream Lane did not end on both peers");
        Console.WriteLine(string.Join(", ", received));
        publisher.Forget(sessionId, StreamDirection.Publish);
        subscriber.Forget(sessionId, StreamDirection.Subscribe);
    }
}
Terminal
dotnet run -p:SampleFile=StreamLaneDemo

Expected result

frame-one, frame-two

Read the Stream Lane contract.

Advanced · 08 / 08

Read Monitor facts through snapshots

C# 3.3.2 projects the startup choice and Core health/stats; it does not invent another connector's Monitor wait API.

Monitoring.cs
using CoAkka.Runtime;

namespace CoAkkaPortal;

internal static class Monitoring
{
    public static async Task Main()
    {
        const string target = "orders.quote";
        var startSpec = new ConnectorStartSpec(
            SystemName: "orders",
            NodeId: "monitor-csharp-1",
            Routes: [RuntimeHost.LocalRoute(target)],
            EnableMonitor: true);

        await using var runtime = RuntimeHost.Start(startSpec);
        runtime.RegisterTextHandler(target, payload => payload);
        await runtime.AskTextAsync(
            source: "checkout",
            target: target,
            payload: "signal",
            timeoutMs: 2_000);
        var startup = runtime.StartupConfig();
        var health = runtime.Health();
        var stats = runtime.Stats();
        Console.WriteLine($"monitor enabled={startup.MonitorEnabled.ToString().ToLowerInvariant()}");
        Console.WriteLine($"state={health.RuntimeState} routes={stats.RouteCount}");
    }
}
Terminal
dotnet run -p:SampleFile=Monitoring

Verified result

monitor enabled=true
state=Started routes=1

Run the configuration lab · Read operations