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.
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.
public sealed class WorldService(WorldLoop loop) : BackgroundService
{
protected override Task ExecuteAsync(CancellationToken stoppingToken) => loop.RunAsync(stoppingToken);
}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.MaxDegreeOfParallelismwhenParallelSystemsworlds and Kestrel share the cores. - Metrics: with
WorldOptions.MeasureSystems, readsystem.Stats(Runs,Last,Average) for each system ofworld.Systemson the loop, between two updates, and publish the numbers with the status (measuring systems). - Health: under
SystemErrorPolicy.Disable, a system with a non-nullErroris 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.Coreis markedIsAotCompatibleand the generated code calls your methods directly, and the publish has no warnings. A generic system closed only by another assembly needsMakeGenericType, 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 stopand Kubernetes sendSIGTERM, 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 of | Do | Why |
|---|---|---|
| A lock around the world for every request | A channel the tick drains | One owner, no lock on the tick |
| A request per read | A status the tick publishes | Reads cost a volatile load, not a tick of latency |
| Publishing every tick | UpdateInterval on the publishing system | The copy is made only when it is due |
| Writing the save file on the tick | Save on the owner, the file write on another thread | The tick waits for encoding only |
| One world for every zone | One world and loop per zone | Worlds 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
Saveand one file write, withinHostOptions.ShutdownTimeout.
Pitfalls
| Mistake | What happens | Caught by |
|---|---|---|
A handler calls world.CreateEntity or entity.Set | Two threads change one world | EECS014 for lambdas handed to Task.Run and the like; the runtime when two changes collide; otherwise nothing |
| A handler reads components directly | Values torn or stale while the tick moves rows | Nothing: publish a copy |
A reply without RunContinuationsAsynchronously | The handler runs inside the tick, on the world's thread | Code review |
Replying with an Entity handle | The handler later touches the world from its own thread | Reply with an EntityId or copied values |
AddSingleton after Load | The loaded singleton is reset | Check HasSingleton<T>() (or the generated HasX) first |
| An unbounded channel | A world that falls behind fills memory | Use Channel.CreateBounded |
| The channel left open on shutdown | A handler that writes after the last drain, or waits on a full channel, never gets its reply | requests.Writer.TryComplete() after the last tick, then answer what is left |
await or blocking IO in a system | The whole tick waits | Hand the IO to the host as data |
Related
Threading
The owner thread, input from other threads and parallel systems.
Saves
What Save writes, and which code changes a save survives.
Testing systems
The same world, built in a test and checked after one update.
Sample: GameLoop
A fixed tick, a mailbox from a network thread and replication of what changed.
Last updated on
How is this guide?
Threading and parallel systems
How EasyEcs uses every core without locks on hot paths: one owner thread per world, parallel stages of non-conflicting systems and parallel [ForEach].
Testing systems
Test EasyEcs systems with a world per test: arrange entities and singletons, call Update, assert on data. Shared setup, errors, allocation budgets, saves.