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 APIWhy 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
refparameters of a[ForEach]method (or aForEachjob) 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 itsWrites) to the entity's new row after the body returns.inparameters keep showing the values from before the change. - A job run on one entity with
entity.Rungets the same guarantee: its refs stay the entity's values across its own structural changes, and the components in itsWritesare carried to the new row when it returns. - Any other
ref(fromentity.Get<T>(), an item of aQueryloop, 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:
- read what you need before awaiting;
- after the await, re-validate through the
Entityhandle, which is version-checked; - 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 hpBob'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 of | Do | Why |
|---|---|---|
Has<T>() then Get<T>() | ref var x = ref e.TryGetRef<T>(out bool found) | One lookup |
Get<T>() several times in a method | One ref local, used before any structural change | One lookup |
Get<T>() to read a tracked component | Read<T>() or the generated property | Not stamped as a write |
| Looking an id up on every access | Look it up once per method with TryGetEntity | The handle then needs no lookup |
| A singleton lookup per call from host code | A SingletonRef<T> kept from setup | No 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):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| HandleAccess | 3.33 μs | 0.26× | 0 B |
| TryGetEntity | 3.60 μs | 0.28× | 0 B |
| SingletonAccess | 1.01 μs | 0.08× | 0 B |
What it costs
- A
refis 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:IsAliveis 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
| Mistake | What happens | Caught by |
|---|---|---|
Changing a copy (var hp = e.Get<Health>()) | The table is unchanged | Code review: ref var |
A ref local across an await | Does not compile | The C# compiler |
A ref kept after a structural change | Points at a stale copy or another entity's row | Code review: get it again |
A raw index stored instead of the EntityId | Names whichever entity reuses the index | Store the EntityId; TryGetEntity checks the version |
An Entity stored in a component | A managed column | EECS017 (warning) |
A DynamicBuffer<T> taken by value | Writes go to a shared list, unstamped | EECS012 |
Touching the world after an await that resumed on the thread pool | Races with the owner thread | Code 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 |
Related
Last updated on
How is this guide?
Cleanup and disable
Release outside resources exactly once with ICleanupComponent, pause a component with Disable<T> and switch whole entities off in a C# ECS.
Change tracking
Visit only the entities whose component was written or removed since a system last ran, with ITrackChanges, [Changed<T>] and [Removed<T>] in C#.