← Tutorials

Async Tasks

Some work takes too long for one frame: parsing a file, computing a path, summing a large table. Turian lets a component start that work on a worker thread and resume on the game thread once it finishes, without blocking the game loop. This tutorial starts a routine that counts seconds on the game clock and runs a computation on a worker, then applies the result to the scene.

This tutorial takes about fifteen minutes. You need the getting-started tutorial done. It is based on the example-10-async example.

1. Create a project

turian-cli new HelloAsync
turian-studio --project HelloAsync

2. Write the component

Create Assets/AsyncDemo.cs:

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

namespace Usercode;

/// <summary>Counts game seconds, and sums numbers on a worker thread before moving the box on the game thread.</summary>
public class AsyncDemo : Component
{
    /// <summary>Whole seconds counted on the game clock, so the time scale applies.</summary>
    [JsonIgnore]
    public int Counted { get; private set; }

    /// <summary>The sum the worker computed.</summary>
    [JsonIgnore]
    public int Sum { get; private set; }

    public override void OnStart()
    {
        Async.Run(CountSeconds);
        Async.Run(SumOnWorker);
    }

    async ValueTask CountSeconds(CancellationToken token)
    {
        try
        {
            while (true)
            {
                await Async.Seconds(1, token);
                Counted++;
                Log.Logger.LogInformation("Counted {Counted} s", Counted);
            }
        }
        finally
        {
            Log.Logger.LogInformation("Counting stopped at {Counted} s", Counted);
        }
    }

    async ValueTask SumOnWorker(CancellationToken token)
    {
        var origin = Async;
        var sum = await Task.Run(static () => Enumerable.Range(1, 1000).Sum(), token).ConfigureAwait(false);
        await origin.MainThread(token);
        Sum = sum;
        Node!.Position = new Vector3(2f, Node.Position.Y, Node.Position.Z);
        Log.Logger.LogInformation("Worker summed to {Sum} on the game thread", Sum);
    }
}

Save it, then check that it compiles:

turian-cli compile HelloAsync

Every component has an Async property. It starts routines and waits that belong to that component: when the component is destroyed or Play Mode stops, its routines are cancelled and their finally blocks run.

3. Attach it and play

Select Box in the Scene Tree, click Add Component in the Inspector and choose AsyncDemo. Press F5.

Two things happen. The Output panel logs Worker summed to 500500 on the game thread, which is the sum of 1 to 1000 computed on a worker. The Box moves to X = 2, because that change runs on the game thread after the worker returns. The counter goes up once a second: the Output panel logs Counted 1 s, Counted 2 s and so on.

Press F5 again. The Output panel logs Counting stopped at N s. That line comes from the finally block, which runs when the play session ends.

4. Pick the right wait

Each Async wait resumes at a different point in the frame. Pick the one whose timing matches your work:

Wait Resumes
Async.NextFrame(token) On a strictly later presentation frame.
Async.FixedUpdate(token) After the next completed fixed simulation tick.
Async.LateUpdate(token) At the next late-update boundary, after every OnUpdate.
Async.Seconds(s, token) After s seconds of scaled time, so the time scale applies.
Async.UnscaledSeconds(s, token) After s seconds that ignore the time scale. Use it for UI timers.
Async.RealtimeSeconds(s, token) After s seconds of monotonic wall time, including time the Studio pause holds.
Async.FixedSeconds(s, token) After s seconds of completed fixed ticks.
Async.Until(predicate, token) Once the predicate returns true, checked after updates.
Async.While(predicate, token) Once the predicate returns false, checked after updates.

Each wait returns a ValueTask, so you await it once. Do not store one and await it twice.

5. Apply results on the game thread

The rule behind step 2 is simple: compute on the worker, and change the scene only after MainThread. Capture the scheduler before you leave the game thread, as var origin = Async; does, and call origin.MainThread(token) after the worker returns. Everything after that line runs on the game thread, where it is safe to touch Node, components and the Inspector values.

Keep the worker code free of scene state. The lambda passed to Task.Run only reads its own inputs and returns a value.

Gotchas

  • Do not call Thread.Sleep or Task.Delay inside a game routine. Use an Async wait, so the timing follows the game clock and Studio pause.
  • A raw Task awaited inside a routine does not get the same shutdown guarantees as an engine wait. Prefer Async waits, and pass the routine's CancellationToken to any Task.Run you start.
  • Coroutines, WhenAll, WhenAny and the end-of-frame rendering hook are not implemented yet. Chain waits one after another, or start several Async.Run routines.
  • A routine that throws is reported against its component in the Output panel. The other routines keep running.

Next steps

Edit this page