Async

Gameplay code often needs to wait: a door stays open for three seconds, a sequence runs one step per frame, a calculation finishes on a worker thread before the result changes the world. Turian's async support lets a component await these things with the Async property. Each wait resumes on the game thread at a known point of the game loop, so gameplay state changes happen on one thread, and a wait stops by itself when its component or the game goes away.

Use Async instead of Task.Delay, which bypasses the game's time and its lifetime rules. The analyzer reports Task.Delay in components.

Starting a routine

Start an async method with Async.Run. The routine receives a cancellation token and returns a ValueTask:

using System.Text.Json.Serialization;
using System.Threading;

namespace Usercode;

public sealed class Ticker : Component
{
    [JsonIgnore]
    public int Ticks { get; private set; }

    public override void OnStart() => Async.Run(CountHalfSeconds);

    async ValueTask CountHalfSeconds(CancellationToken cancellationToken)
    {
        while (true)
        {
            await Async.Seconds(0.5, cancellationToken);
            Ticks++;
        }
    }
}

Run returns at once. The routine continues on the game thread after each await. The examples start their routines from OnStart.

Choosing a wait

Each wait returns a ValueTask that completes at a different point in the frame:

Wait Completes
NextFrame() On a later frame, after that frame's updates.
FixedUpdate() After the next fixed step succeeds.
LateUpdate() At the next late-update point, after OnLateUpdate.
Seconds(s) When s seconds of scaled game time have passed. Time scale and pause affect it.
UnscaledSeconds(s) When s seconds of presentation time have passed, ignoring time scale. It freezes while Studio is paused.
RealtimeSeconds(s) When s seconds of wall-clock time have passed. It keeps counting while Studio is paused, so it can finish late.
FixedSeconds(s) When s seconds of completed simulation time have passed.
Until(predicate) When the predicate returns true. It is checked once per frame.
While(predicate) When the predicate returns false. It is checked once per frame.
MainThread() Back on the game thread, at the next update point.

Use Seconds for gameplay timing, UnscaledSeconds for a menu or a UI timer that should keep time when the game is slowed, and FixedSeconds when the timing must match the simulation exactly. RealtimeSeconds is for measuring elapsed wall time.

Running work off the main thread

Compute on a worker, then come back to the game thread before you touch component state. Capture the Async source on the game thread first, because Async is read from the component:

using System.Text.Json.Serialization;
using System.Threading;

namespace Usercode;

public sealed class Summer : Component
{
    [JsonIgnore]
    public int Total { get; private set; }

    public override void OnStart() => Async.Run(ComputeOnWorker);

    async ValueTask ComputeOnWorker(CancellationToken token)
    {
        var origin = Async;
        var sum = await Task.Run(static () => Enumerable.Range(1, 1000).Sum(), token).ConfigureAwait(false);
        await origin.MainThread(token);
        Total = sum;
    }
}

Three rules keep this safe:

  • Pass the token into Task.Run, so the work stops when the routine is canceled.
  • Change component state only after MainThread returns. Worker code must not touch nodes, components or scene objects.
  • An engine wait always resumes on the game thread, even after ConfigureAwait(false). Only a raw Task from another library runs its continuation on whatever thread completed it, so return with MainThread after it.

Cancellation

A routine stops for three reasons, and each one cancels the wait it is in:

  • The component is destroyed. Every routine started with Async.Run receives a token that is canceled when its component is destroyed. The cancellation happens before OnDisable and OnDestroy run.
  • The game stops. Stopping Play cancels every engine wait and runs each routine's cleanup.
  • You cancel it. Pass your own token into the wait, linked with the routine's token so the routine still stops with its component:
using System.Text.Json.Serialization;
using System.Threading;

namespace Usercode;

public sealed class Door : Component
{
    readonly CancellationTokenSource close = new();

    [JsonIgnore]
    public bool Closed { get; private set; }

    public override void OnStart() => Async.Run(WaitThenClose);

    public void CancelClosing() => close.Cancel();

    async ValueTask WaitThenClose(CancellationToken lifetime)
    {
        using var linked = CancellationTokenSource.CreateLinkedTokenSource(lifetime, close.Token);
        try
        {
            await Async.Seconds(3, linked.Token);
            Closed = true;
        }
        catch (OperationCanceledException) when (close.IsCancellationRequested)
        {
            // Canceled on purpose: keep the door open.
        }
    }

    public override void OnDestroy() => close.Dispose();
}

A canceled wait throws OperationCanceledException where it was awaited. Use a finally block for cleanup that must run however the routine ends, and catch the exception only when you can tell a deliberate cancel from the others, as above. Cancellation of one routine does not affect the others on the same component.

Failures

An exception that leaves a routine is reported to the log with the component's name and its node's name. The other routines keep running, and the game keeps running too. Cancellations that the lifetime caused are expected and are not reported.

Rules and analyzers

The engine's analyzers check these rules for components:

  • An async method in a component must return Task or ValueTask, not void. An async void method in a component, including a lambda or local function inside one, is a compile error (TUR0002).
  • Do not call Task.Delay. Use the component's Async waits (TUR0003, a warning).
  • Do not store a ValueTask in a field. A ValueTask may be awaited once. Store a Task when several places need the result (TUR0004, a warning).
  • Await each ValueTask exactly once. Awaiting it again throws.

What is not available yet

The current scheduler has no coroutines, no WhenAll or WhenAny, and no end-of-frame rendering wait. Compose the waits above in your own routines instead.

Next steps


← All docs Edit this page