异步任务
有些工作耗时太长,无法在一帧内完成:解析文件、计算路径、累加大型表格。Turian 允许组件将这类工作启动到工作线程上,并在其完成后恢复到游戏线程,同时不阻塞游戏循环。本教程将启动一个按游戏时钟计秒的例程,并在工作线程上执行一次计算,然后把结果应用到场景中。
本教程大约需要十五分钟。您需要先完成入门教程。它基于 example-10-async 示例。
1. 创建项目
turian-cli new HelloAsync
turian-studio --project HelloAsync
2. 编写组件
创建 Assets/AsyncDemo.cs:
using System.Text.Json.Serialization;
using System.Threading;
namespace Usercode;
/// <summary>统计游戏秒数,并在工作线程上求和,然后在游戏线程上移动方块。</summary>
public class AsyncDemo : Component
{
/// <summary>在游戏时钟上统计的整秒数,因此时间缩放会生效。</summary>
[JsonIgnore]
public int Counted { get; private set; }
/// <summary>工作线程计算出的和。</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);
}
}
保存后,检查它是否可以编译:
turian-cli compile HelloAsync
每个组件都有一个 Async 属性。它用于启动和等待属于该组件的例程:当组件被销毁或 Play Mode 停止时,它的例程会被取消,并且其 finally 块会运行。
3. 添加组件并运行
在 Scene Tree 中选中 Box,在 Inspector 中点击 Add Component,然后选择 AsyncDemo。按 F5。
会发生两件事。Output 面板会记录 Worker summed to 500500 on the game thread,这是在工作线程上计算出的 1 到 1000 之和。Box 会移动到 X = 2,因为该更改是在工作线程返回后于游戏线程上运行的。计数器每秒增加一次:Output 面板会记录 Counted 1 s、Counted 2 s,依此类推。
再次按 F5。Output 面板会记录 Counting stopped at N s。该行来自 finally 块,它在播放会话结束时运行。
4. 选择合适的等待方式
每个 Async 等待都会在帧中的不同时刻恢复。请选择时机与您的工作相匹配的那一个:
| 等待 | 恢复时机 |
|---|---|
Async.NextFrame(token) |
在严格晚于当前的呈现帧上。 |
Async.FixedUpdate(token) |
在下一个已完成的固定模拟 tick 之后。 |
Async.LateUpdate(token) |
在下一个 late-update 边界上,即所有 OnUpdate 之后。 |
Async.Seconds(s, token) |
在 s 秒的缩放时间之后,因此时间缩放会生效。 |
Async.UnscaledSeconds(s, token) |
在 s 秒之后,忽略时间缩放。用于 UI 计时器。 |
Async.RealtimeSeconds(s, token) |
在 s 秒的单调墙钟时间之后,包括 Studio 暂停所占用的时间。 |
Async.FixedSeconds(s, token) |
在 s 秒已完成的固定 tick 之后。 |
Async.Until(predicate, token) |
当谓词返回 true 时,于更新之后检查。 |
Async.While(predicate, token) |
当谓词返回 false 时,于更新之后检查。 |
每个等待都会返回一个 ValueTask,因此您只需 await 它一次。不要保存一个等待对象并将其 await 两次。
5. 在游戏线程上应用结果
第 2 步背后的规则很简单:在工作线程上计算,并且只在 MainThread 之后修改场景。像 var origin = Async; 那样,在离开游戏线程之前捕获调度器,并在工作线程返回后调用 origin.MainThread(token)。该行之后的所有代码都在游戏线程上运行,在那里访问 Node、组件和 Inspector 中的值是安全的。
请保持工作线程的代码不涉及场景状态。传给 Task.Run 的 lambda 只读取它自己的输入并返回一个值。
注意事项
- 不要在游戏例程中调用
Thread.Sleep或Task.Delay。请使用Async等待,这样时间才会遵循游戏时钟和 Studio 的暂停。 - 在例程中 await 的原始
Task不具备引擎等待所提供的关闭保证。应优先使用Async等待,并将例程的CancellationToken传给您启动的任何Task.Run。 - Coroutine、
WhenAll、WhenAny以及帧末渲染钩子目前尚未实现。请依次串联等待,或启动多个Async.Run例程。 - 抛出异常的例程会在 Output 面板中被报告到其所属组件下,其他例程会继续运行。
下一步
- 专用服务器:从同一个项目构建客户端和无界面服务器。
- 导出到 Android:在手机上运行同一个项目。
- Components:您的例程所挂接的生命周期。
- Output 面板:日志和例程失败信息出现的位置。