EasyEcs

Hosting a C# ECS in .NET services

Host EasyEcs in ASP.NET Core or a Worker for game servers, simulations and real-time backends: one owner runs the tick and bounded channels carry requests.

An ECS-powered game server, simulation or real-time backend can host EasyEcs in ASP.NET Core or a Worker Service: request handlers, sockets and timers run on the thread pool, while a world takes structural changes from one thread at a time. Give the world one owner, a hosted service that builds it, runs its tick and saves it when the host stops, and let everything else talk to it through a channel. EasyEcs provides the ECS world, not network transport or a complete application framework. It needs no hosting package for this pattern: the host and channel are a few classes of your own.

When to use it

Use it for

A game server, simulation or matchmaker inside ASP.NET Core, a Worker Service or any app built on Microsoft.Extensions.Hosting, with HTTP endpoints, health checks and metrics next to the world.

Skip it for

A console tool, a benchmark or a test: new World() and a loop are enough (getting started, testing). Do not share one world between request handlers behind a lock: a lock around every request serializes the server anyway, and reads without it race with the tick.

How to use it

Everything that is not the world's owner reaches it through two doors: a channel of requests the tick drains, and an immutable status the tick publishes.

requests

replies

publishes

reads

start, stop

HTTP handlers, sockets

Channel

World loop: Update

Status

Host

Give the world one owner

One object owns the world, and only its loop touches it. A PeriodicTimer sets the tick; every world.Update() runs all systems synchronously and returns before the next await.

public sealed class WorldLoop(World world)
{
    private readonly World _world = world;

    public async Task RunAsync(CancellationToken stop)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(50));   // 20 ticks per second
        try
        {
            while (await timer.WaitForNextTickAsync(stop))
                _world.Update();
        }
        catch (OperationCanceledException)
        {
            // the host is stopping
        }
    }
}

After an await, the loop may resume on another thread-pool thread. That is allowed: the owner is whoever changes the world, one at a time, and each await orders one tick after the other. Use a dedicated thread (new Thread, or Task.Factory.StartNew with TaskCreationOptions.LongRunning) when the tick needs steadier timing than a busy thread pool gives.

Start and stop with the host

A BackgroundService runs the loop for the life of the app. On Ctrl+C or SIGTERM the host cancels the token and waits for ExecuteAsync to finish, up to HostOptions.ShutdownTimeout (30 seconds by default), so a final save fits there.

WorldService.cs
public sealed class WorldService(WorldLoop loop) : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken) => loop.RunAsync(stoppingToken);
}
Program.cs
using EasyEcs;

var builder = Host.CreateApplicationBuilder(args);

var world = new World();
builder.Services.AddSingleton(new WorldLoop(world));
builder.Services.AddHostedService<WorldService>();

builder.Build().Run();

These two blocks are skipped by the docs' compile check only because it does not reference Microsoft.Extensions.Hosting; in a Worker Service or ASP.NET Core project they build as they are.

An exception that leaves Update() (a system threw, under the default SystemErrorPolicy.Throw) ends ExecuteAsync, and the host stops: the process fails fast and the platform restarts it. With new WorldOptions { SystemErrors = SystemErrorPolicy.Disable } the failing system is switched off instead and the tick goes on; report its system.Error from a health check (errors).

Hand requests to the world

A request is a message, not a component. Handlers write it into a bounded Channel<T>; a system drains the channel at the start of each tick and turns each message into data. A request that needs an answer carries a TaskCompletionSource<T> the system completes:

using System.Threading.Channels;

public readonly record struct SpawnRequest(float X, float Y, TaskCompletionSource<EntityId> Reply);

public sealed class ReceiveSpawns(ChannelReader<SpawnRequest> requests) : EcsSystem
{
    private readonly ChannelReader<SpawnRequest> _requests = requests;   // a dependency: allowed (EECS007)

    protected override void OnUpdate()
    {
        while (_requests.TryRead(out var request))
        {
            var unit = World.CreateEntity(new Position(request.X, request.Y));
            request.Reply.TrySetResult(unit.Id);                       // answer with an id, never a handle
        }
    }
}

Create each reply with TaskCreationOptions.RunContinuationsAsynchronously. Without it, TrySetResult runs the handler's continuation inline, on the world's thread, in the middle of the tick. Answer with an EntityId or a copy of the values: an Entity handle used by the handler later would touch the world from another thread.

Bound the channel (Channel.CreateBounded) so a world that falls behind slows its callers down (BoundedChannelFullMode.Wait) or refuses them (DropWrite, TryWrite returning false) instead of growing without limit. The threading guide shows the same pattern with a plain ConcurrentQueue<T>. The reader lives in a readonly field of the system, not in a singleton: World.Save writes every singleton, and a channel has no formatter.

On shutdown, complete the writer (requests.Writer.TryComplete()) after the last tick, then answer what is still in the channel. A handler that writes after that gets a ChannelClosedException at once instead of a reply that never comes (full example, Arena.RunAsync).

A request about an entity that exists already carries its EntityId. The system finds the entity and runs a job on it with entity.Run: one lookup for all the job's components, and a filter that rules out a dead unit. Run returns false when the entity is gone, fails the filter or lacks a component, which is the reply:

using System.Threading.Channels;

public readonly record struct HealRequest(EntityId Unit, int Amount, TaskCompletionSource<bool> Reply);

public struct Heal : IForEachEntity<Health>
{
    public int Amount;
    public static int Writes => 1;

    public void Execute(Entity unit, ref Health health) => health.Value += Amount;
}

public sealed class ReceiveHeals(ChannelReader<HealRequest> requests) : EcsSystem
{
    private static readonly QueryFilter Alive = QueryFilter.Create().Without<Dead>();   // built once
    private readonly ChannelReader<HealRequest> _requests = requests;

    protected override void OnUpdate()
    {
        while (_requests.TryRead(out var request))
        {
            var heal = new Heal { Amount = request.Amount };
            bool healed = World.TryGetEntity(request.Unit, out var unit)
                && unit.Run<Health, Heal>(ref heal, Alive);                // false: gone, dead or no Health
            request.Reply.TrySetResult(healed);
        }
    }
}

Let handlers read without a round trip

Handlers never read the world directly: component values are not synchronized, and the tick moves and rewrites rows while a handler would read them. Instead, a system copies what handlers may see into an immutable object and publishes it with one atomic write; handlers read the latest copy without waiting for a tick:

public sealed record ArenaStatus(long Tick, int Units);

public sealed class StatusBoard
{
    private ArenaStatus _current = new(Tick: 0, Units: 0);

    public ArenaStatus Current => Volatile.Read(ref _current);

    public void Publish(ArenaStatus status) => Volatile.Write(ref _current, status);
}

public sealed class PublishStatus(StatusBoard board) : EcsSystem
{
    private readonly StatusBoard _board = board;

    public override int UpdateInterval => 20;                          // once a second at 20 Hz

    protected override void OnUpdate() =>
        _board.Publish(new ArenaStatus(World.UpdateCount, World.Count<Position>()));
}

UpdateInterval keeps the copy (and its allocation) off most ticks. A read that must see the state of this very tick goes through the channel as a request with a reply, like a write.

Load at start, save at stop

Load the last save before the first tick, then add only the singletons the save did not hold: Load replaces the world's singletons, and AddSingleton would reset one that was loaded. Save after the loop ends, into a temporary file moved over the old one, so a crash during the write never leaves half a save. When systems save or replicate [Changed<T>] rows, load with markWritten: false, so the first tick does not send the loaded world again (restart):

using Nino.Core;

public static class Persistence
{
    public static void LoadOrStart(World world, string path)
    {
        if (File.Exists(path))
            world.Load(File.ReadAllBytes(path));
        if (!world.HasClock)
            world.AddSingleton<Clock>();
    }

    public static void Save(World world, string path)
    {
        var output = new NinoArrayBufferWriter();
        world.Save(output);
        File.WriteAllBytes(path + ".tmp", output.WrittenSpan);
        File.Move(path + ".tmp", path, overwrite: true);
    }
}

public record struct Clock(long Tick) : ISingletonComponent;

For autosaves while the server runs, call Save on the owner between two ticks, then hand the bytes to another thread for the disk write: the world is only needed while it encodes. What a save holds and what survives a code change are in saves.

Several worlds, health and metrics

  • Several worlds: one loop per world, each its own owner (one hosted service per zone, or one service that starts a loop per world). They share nothing, so they need no locks (one world per thread). Lower WorldOptions.MaxDegreeOfParallelism when ParallelSystems worlds and Kestrel share the cores.
  • Metrics: with WorldOptions.MeasureSystems, read system.Stats (Runs, Last, Average) for each system of world.Systems on the loop, between two updates, and publish the numbers with the status (measuring systems).
  • Health: under SystemErrorPolicy.Disable, a system with a non-null Error is switched off; publish that list and let the health check report it.

Deploy

  • Native AOT: <PublishAot>true</PublishAot> publishes the world and its systems as a native executable: EasyEcs.Core is marked IsAotCompatible and the generated code calls your methods directly, and the publish has no warnings. A generic system closed only by another assembly needs MakeGenericType, which Native AOT cannot do (FAQ). ASP.NET Core has AOT rules of its own (WebApplication.CreateSlimBuilder, JSON source generation): see Microsoft's Native AOT guide for ASP.NET Core.
  • Containers: docker stop and Kubernetes send SIGTERM, which the host turns into the shutdown above. Give the container a grace period longer than the final save.
  • No IO in systems: a system that awaits or blocks stalls the whole tick. Systems hand IO out as data (a request in a queue, bytes in an outbox) and the host does it outside Update().

Full example

An ASP.NET Core server with one arena: POST /units spawns a unit and answers with its id, GET /status reads the copy the world publishes once a second, and the world is saved on shutdown and loaded on the next start. Create it with dotnet new web -n Arena, add dotnet add package EasyEcs, and replace Program.cs with these files.

Run it with dotnet run --urls http://localhost:5000. In a second terminal, spawn two units and read the status; then stop the server with Ctrl+C, start it again, and repeat:

$ curl -X POST "localhost:5000/units?x=0&y=0"
{"index":0,"version":1}
$ curl -X POST "localhost:5000/units?x=5&y=5"
{"index":1,"version":1}
$ curl localhost:5000/status
{"tick":60,"units":2}

$ curl -X POST "localhost:5000/units?x=0&y=0"
{"index":2,"version":1}
$ curl -X POST "localhost:5000/units?x=5&y=5"
{"index":3,"version":1}
$ curl localhost:5000/status
{"tick":125,"units":4}

The second run starts from the save: the two units of the first run are still there (four units in all), new ids continue after theirs, and the clock goes on from where it stopped instead of starting at zero. The status is at most a second old, and reading it never waits for the world.

How to use it fast

Instead ofDoWhy
A lock around the world for every requestA channel the tick drainsOne owner, no lock on the tick
A request per readA status the tick publishesReads cost a volatile load, not a tick of latency
Publishing every tickUpdateInterval on the publishing systemThe copy is made only when it is due
Writing the save file on the tickSave on the owner, the file write on another threadThe tick waits for encoding only
One world for every zoneOne world and loop per zoneWorlds share nothing and scale across cores

The tick itself is the cost that matters. A world of 100,000 entities updates in 1.72 ms per tick, allocating 0 B (WorldSimulationBenchmark), so a 20 Hz tick leaves the rest of each 50 ms to request handlers.

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

What it costs

  • The loop: one timer and one Update() per tick; nothing allocated by EasyEcs.
  • A request: a channel write and read, plus the reply's TaskCompletionSource (allocated per request, on the handler's side).
  • A status: one immutable object per publish, read with a volatile load.
  • Shutdown: one Save and one file write, within HostOptions.ShutdownTimeout.

Pitfalls

MistakeWhat happensCaught by
A handler calls world.CreateEntity or entity.SetTwo threads change one worldEECS014 for lambdas handed to Task.Run and the like; the runtime when two changes collide; otherwise nothing
A handler reads components directlyValues torn or stale while the tick moves rowsNothing: publish a copy
A reply without RunContinuationsAsynchronouslyThe handler runs inside the tick, on the world's threadCode review
Replying with an Entity handleThe handler later touches the world from its own threadReply with an EntityId or copied values
AddSingleton after LoadThe loaded singleton is resetCheck HasSingleton<T>() (or the generated HasX) first
An unbounded channelA world that falls behind fills memoryUse Channel.CreateBounded
The channel left open on shutdownA handler that writes after the last drain, or waits on a full channel, never gets its replyrequests.Writer.TryComplete() after the last tick, then answer what is left
await or blocking IO in a systemThe whole tick waitsHand the IO to the host as data
Edit on GitHub

Last updated on

How is this guide?

On this page