EasyEcs

ref and await

Change components through a ref. Which refs survive a structural change, why none may cross an await, and how async code reaches the world safely.

Components are structs stored in the columns of tables. entity.Get<T>() returns a ref into that column: changing it changes the entity, with no copy and no second lookup. A copy changes nothing. And because rows move when entities change, a ref is valid only until the next structural change, so it never crosses an await: after one, you re-acquire the data through the Entity handle, which tells you whether the entity is still there.

When to use it

Use it for

Every write of a component: ref var hp = ref unit.Get<Health>(), the generated unit.Health.Value -= 10, ref parameters of [ForEach] methods. Short-lived refs inside one method, used before the next structural change.

Skip it for

Keeping data across time: a ref in a field, across an await, or across a structural change. Keep the Entity (or its EntityId) instead and look the data up again. Reading a tracked component: use Read<T>() or the generated property, so the read is not stamped as a write.

How to use it

Copies and refs

var copy = entity.Health;              // a copy: the change below is lost
copy.Value -= 10;

ref var hp = ref entity.Health;        // a ref into the table
hp.Value -= 10;
entity.Health.Value -= 10;             // the same, inline
entity.Get<Health>().Value -= 10;      // the same, through the generic API

Why a ref expires

A ref into a table is valid only until the next structural change, of any entity:

  • an entity's row is copied to another table when it gains a component its table has no column for;
  • the last row of a table fills the row of an entity that left it;
  • a full table is reallocated when it grows.

An old ref then silently points at a stale copy or at another entity's data. Which change moves which row is an implementation detail, and the change may come from your code or from another system, so treat every structural change as one that may invalidate your refs.

Inside passes

Use ref freely inside [ForEach] methods, ForEach jobs and Query loops: each entity gets fresh refs.

  • The ref parameters of a [ForEach] method (or a ForEach job) stay writable even when the body changes the archetype of the entity it visits: the pass copies those writes (for a job, the components in its Writes) to the entity's new row after the body returns. in parameters keep showing the values from before the change.
  • A job run on one entity with entity.Run gets the same guarantee: its refs stay the entity's values across its own structural changes, and the components in its Writes are carried to the new row when it returns.
  • Any other ref (from entity.Get<T>(), an item of a Query loop, or into another entity) is guaranteed only until the next structural change. Write through it before the change, or get it again afterwards.
public record struct Target(EntityId Id) : IComponent;

public class StrikeSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Strike(Entity attacker, in Target target, World world)
    {
        if (!world.TryGetEntity(target.Id, out var victim) || !victim.HasHealth) return;
        ref var hp = ref victim.Health;
        hp.Value -= 10;                                   // write first...
        if (hp.Value <= 0) victim.SetDead();              // ...then change structure: hp may now be stale
        attacker.RemoveTarget();                          // structural too; refs taken before it are not used after it
    }
}

Across await

C# forbids a ref local that lives across an await; do not smuggle one through Unsafe, pointers or Span fields either. While you await, other code runs: it may add entities or components (moving and reallocating storage), or destroy your entity and recycle its index. So:

  1. read what you need before awaiting;
  2. after the await, re-validate through the Entity handle, which is version-checked;
  3. write back through a newly acquired ref.
public record struct Account(long Id) : IComponent;

public interface IShop
{
    ValueTask<int> RedeemPotionAsync(long accountId);
}

public static class Potions
{
    // Runs on the world's owner thread, and resumes there (a single-threaded server loop).
    public static async ValueTask HealFromStoreAsync(Entity player, IShop shop)
    {
        long id = player.Account.Id;                       // read what you need before awaiting
        int heal = await shop.RedeemPotionAsync(id);      // the world may change meanwhile
        if (player.IsAlive && player.HasHealth)           // re-validate after the await
            player.Health.Value += heal;                  // a fresh ref into current storage
    }
}

This is only correct when the code after the await runs on the world's owner thread, for example a server loop with its own single-threaded SynchronizationContext. If the continuation may resume on the thread pool, it must not touch the world at all: hand the result to the owner thread as data, and let a system apply it.

using System.Collections.Concurrent;

public record struct PotionRedeemed(EntityId Player, int Heal);   // a message, not a component

// The queue is a dependency in a readonly field, which EECS007 allows. A managed queue in a singleton
// would make World.Save need a formatter for it.
public sealed class ApplyRedemptions(ConcurrentQueue<PotionRedeemed> inbox) : EcsSystem
{
    private readonly ConcurrentQueue<PotionRedeemed> _inbox = inbox;   // filled by async code on any thread

    protected override void OnUpdate()
    {
        while (_inbox.TryDequeue(out var done))
            if (World.TryGetEntity(done.Player, out var player) && player.HasHealth)
                player.Health.Value += done.Heal;                     // on the owner thread, during the update
    }
}

The system takes the queue through its constructor, so AddSystem<T>() cannot create it: add an instance. The async side reads what it needs on the owner thread, then only enqueues:

var inbox = new ConcurrentQueue<PotionRedeemed>();
world.AddSystem(new ApplyRedemptions(inbox));
public static class PotionOrders
{
    public static async ValueTask RedeemAsync(
        EntityId player, long accountId, IShop shop, ConcurrentQueue<PotionRedeemed> inbox)
    {
        int heal = await shop.RedeemPotionAsync(accountId);   // may resume on any thread
        inbox.Enqueue(new PotionRedeemed(player, heal));      // data for the owner thread, nothing else
    }
}

More on owner threads and input from other threads: Threading.

The exception: singletons

A singleton's storage never moves, so world.SingletonRef<T>() returns a handle you can keep, in a field of your host or across ticks (Singletons). It is still owner-thread data: keep it, but only touch it on the owner thread.

Full example

Two players redeem a potion from a remote shop. While the shop answers, one of them leaves and a new entity reuses his index; the system that applies the answers on the owner thread tells them apart by the EntityId's version. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

bob was 1v1, carol is 1v2
  dropped: 1v1 is gone
alice 65 hp, carol 10 hp

Bob's answer names 1v1, and the entity on index 1 is now 1v2, so TryGetEntity fails and Carol keeps her 10 hp: an id kept across the await never reaches the wrong entity, and only the system, on the owner thread, writes.

How to use it fast

Instead ofDoWhy
Has<T>() then Get<T>()ref var x = ref e.TryGetRef<T>(out bool found)One lookup
Get<T>() several times in a methodOne ref local, used before any structural changeOne lookup
Get<T>() to read a tracked componentRead<T>() or the generated propertyNot stamped as a write
Looking an id up on every accessLook it up once per method with TryGetEntityThe handle then needs no lookup
A singleton lookup per call from host codeA SingletonRef<T> kept from setupNo lookup at all

1,000 component writes through entity handles, the same after looking each id up with TryGetEntity, and 1,000 singleton accesses (MicroBenchmarks):

CaseMeanvs baselineAllocated
HandleAccess3.33 μs0.26×0 B
TryGetEntity3.60 μs0.28×0 B
SingletonAccess1.01 μs0.08×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

What it costs

  • A ref is a pointer into a column: no copy, no lookup after the one that produced it.
  • Getting it through a handle: the entity's 16-byte record, then one cache line of the table's lookup.
  • Re-validating after an await: IsAlive is one record load and a version compare.
  • Carrying [ForEach] writes across a structural change costs one copy of the written components, only for the entities whose table changed.

Pitfalls

MistakeWhat happensCaught by
Changing a copy (var hp = e.Get<Health>())The table is unchangedCode review: ref var
A ref local across an awaitDoes not compileThe C# compiler
A ref kept after a structural changePoints at a stale copy or another entity's rowCode review: get it again
A raw index stored instead of the EntityIdNames whichever entity reuses the indexStore the EntityId; TryGetEntity checks the version
An Entity stored in a componentA managed columnEECS017 (warning)
A DynamicBuffer<T> taken by valueWrites go to a shared list, unstampedEECS012
Touching the world after an await that resumed on the thread poolRaces with the owner threadCode review: hand the result over as data. EECS014 catches only structural changes in a delegate handed to another thread (Task.Run, Parallel.*), not value writes or code after an await
Edit on GitHub

Last updated on

How is this guide?

On this page