> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/async-patterns.md).

# 异步模式

使用 async/await、协程、链式调用、进度跟踪、取消和流来处理 IConvaiOperation\<T> 和 IConvaiStream\<T>。

`IConvaiOperation<T>` 和 `IConvaiStream<T>` 支持多种消费模式，因此你可以选择最适合代码库的风格——纯 async/await、Unity 协程，或两者混用。有关类型定义和成员的参考信息，请参阅 [操作与流类型](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/operation-and-stream-types.md).

***

### Async/await

这是最直接的模式。可用于任何 `async` 方法。操作失败时会抛出 `ConvaiOperationException`.

```csharp
using Convai.Runtime.Core.Async;
using Convai.Runtime.Facades;
using System.Threading;
using UnityEngine;

public class AsyncConnectExample : MonoBehaviour
{
    private async void Start()
    {
        var manager = ConvaiManager.ActiveManager;
        if (manager == null) return;

        try
        {
            var session = await manager.ConnectAsync(destroyCancellationToken);
            Debug.Log($"Connected. Room: {session.RoomId}");
        }
        catch (ConvaiOperationException ex)
        {
            Debug.LogError($"[{ex.Code}] Connect failed: {ex.Message}");
        }
        catch (OperationCanceledException)
        {
            Debug.Log("Connect canceled — scene unloaded.");
        }
    }
}
```

#### `await operation` 与 `await operation.AsTask()`

两者产生相同的结果。建议直接使用 `await operation` ——它使用 `GetAwaiter()` 并避免额外的内存分配。仅在需要将该操作传递给要求 `AsTask()` 的方法时使用，例如 `Task<T>`，如 `Task.WhenAll`.

```csharp
// 直接 await — 推荐
var session = await manager.ConnectAsync();

// AsTask — 仅在需要时使用
await Task.WhenAll(
    manager.ConnectAsync().AsTask(),
    someOtherTask
);
```

***

### 协程

当脚本无法使用 `async` 时（例如，不支持 async 的 Unity 事件回调），或当你更喜欢基于回调的流程时，请使用协程。

```csharp
using Convai.Runtime.Core.Async;
using Convai.Runtime.Facades;
using System.Collections;
using UnityEngine;

public class CoroutineConnectExample : MonoBehaviour
{
    private void Start()
    {
        var op = ConvaiManager.ActiveManager.ConnectAsync();
        StartCoroutine(op.ToCoroutine(
            onSuccess: session => Debug.Log($"Connected: {session.RoomId}"),
            onError:   err     => Debug.LogError($"[{err.Code}] {err.Message}")
        ));
    }
}
```

`ToCoroutine` 让出执行权，直到操作完成。 `onSuccess` 和 `onError` 均为可选项——如果不需要某个回调，请为其传入 `null` 。

{% hint style="warning" %}
在协程中，失败的操作 **不会** 抛出异常。如果省略 `onError` 回调，失败将不会被报告。

```csharp
// 错误——失败不会被报告
yield return op.ToCoroutine(onSuccess: result => Use(result));

// 正确
yield return op.ToCoroutine(
    onSuccess: result => Use(result),
    onError:   err    => Debug.LogError(err.Message));
```

{% endhint %}

***

### ContinueWith 链式调用

将一个操作的结果转换为另一个操作，无需嵌套 `await` 调用。

```csharp
// 同步转换
IConvaiOperation<string> roomIdOp = manager
    .ConnectAsync()
    .ContinueWith(session => session.RoomId);

string roomId = await roomIdOp;

// 异步转换——选择器返回 Task<TNext>
IConvaiOperation<string> nameOp = manager
    .ConnectAsync()
    .ContinueWith(async session =>
    {
        await SomeAsyncLookup(session.RoomId);
        return session.RoomId;
    });
```

`ContinueWith` 会传播错误：如果源操作失败，链式操作也会以相同的错误失败，而不会调用选择器。

***

### 进度跟踪

轮询 `operation.Progress` 以驱动 UI 进度指示器。随着操作的进行，该值会从 `0.0` 增加到 `1.0` 。并非所有操作都会报告细粒度的进度——请检查 `Status` 以确定操作是否已完成。

```csharp
using Convai.Runtime.Facades;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class ConnectProgressBar : MonoBehaviour
{
    [SerializeField] private Slider _progressBar;

    private IEnumerator ConnectWithProgress()
    {
        var op = ConvaiManager.ActiveManager.ConnectAsync();

        while (!op.IsCompleted)
        {
            _progressBar.value = op.Progress;
            yield return null;
        }

        _progressBar.value = 1f;

        if (op.HasError)
            Debug.LogError($"Connect failed: {op.Error.Message}");
    }
}
```

***

### 取消

#### 使用 `CancellationToken`

将 `CancellationToken` 传递给任意 SDK 方法。令牌发出信号后，操作将转换为 `Canceled` 状态。

```csharp
private CancellationTokenSource _cts;

private async void OnEnable()
{
    _cts = new CancellationTokenSource();

    try
    {
        await ConvaiManager.ActiveManager.ConnectAsync(_cts.Token);
    }
    catch (OperationCanceledException) { /* expected */ }
}

private void OnDisable()
{
    _cts?.Cancel();
    _cts?.Dispose();
}
```

#### 使用 `destroyCancellationToken`

`MonoBehaviour.destroyCancellationToken` 对于生命周期受组件控制的操作，这是最简单的取消模式——组件销毁时会自动发出令牌信号。

```csharp
private async void Start()
{
    await ConvaiManager.ActiveManager.ConnectAsync(destroyCancellationToken);
}
```

#### 使用 `operation.Cancel()`

直接在操作句柄上调用 `Cancel()` 即可手动取消操作，不依赖于 `CancellationToken`.

```csharp
var op = manager.ConnectAsync();

// 稍后——取消操作
op.Cancel();
```

#### `CancellationToken` 对比 `operation.Cancel()`

|          | `CancellationToken`           | `operation.Cancel()` |
| -------- | ----------------------------- | -------------------- |
| **来源**   | 外部（`CancellationTokenSource`) | 操作句柄                 |
| **适用场景** | 组件生命周期、超时、链接取消                | 通过按钮或事件取消单个操作        |
| **兼容协程** | 在创建操作时传入                      | 随时在句柄上调用             |

***

### 流

使用 `IConvaiStream<T>` 配合 `await foreach` 和 `await using` 用于清理资源。

```csharp
await using var stream = GetTokenStream();

await foreach (var token in stream.ReadAllAsync(destroyCancellationToken))
{
    AppendToTranscriptUI(token);
}
```

`ReadAllAsync` 返回 `IAsyncEnumerable<T>`。当流进入以下状态时，循环会退出： `Completed`, `Faulted`或 `Canceled`。请务必使用 `await using` ，这样即使循环提前退出，也会调用 `DisposeAsync()` 。

{% hint style="danger" %}
切勿使用 `.Result` 阻塞 Unity 主线程——这会导致死锁。

```csharp
// 错误 — 会在主线程上造成死锁
var session = manager.ConnectAsync().AsTask().Result;
```

请改用 `await` 或 `ToCoroutine()` 。
{% endhint %}

务必释放流。未使用 `await using` 处理流会导致底层资源泄漏。

```csharp
// 错误 — 未释放资源
var stream = GetTokenStream();
await foreach (var item in stream.ReadAllAsync()) { ... }

// 正确
await using var stream = GetTokenStream();
await foreach (var item in stream.ReadAllAsync()) { ... }
```

***

### 错误处理决策表

| 场景                            | 模式                              | 原因                       |
| ----------------------------- | ------------------------------- | ------------------------ |
| `async void` MonoBehaviour 方法 | 使用 async/await 和 try/catch      | 天然适用；错误会以异常形式显现          |
| UI 按钮回调（不支持异步）                | 使用协程和 `onError` 回调              | 按钮回调是同步的                 |
| 带转换的顺序操作                      | ContinueWith 链式调用               | 避免嵌套 await；自动传播错误        |
| 进度条或加载遮罩                      | 协程轮询 `Progress`                 | `yield return null` 每帧循环 |
| 按组件生命周期限定作用域                  | `destroyCancellationToken`      | 无需样板代码；自动清理              |
| 由用户触发取消（按钮）                   | `operation.Cancel()`            | 无需 CTS，直接控制句柄            |
| 连续数据流                         | `await foreach` + `await using` | IAsyncEnumerable + 保证释放  |

***

### 使用示例

#### 示例 1 — 带进度条和取消按钮的加载遮罩

在一个医学培训模拟中，连接会话时会显示加载遮罩，其中包含可视化进度条和取消按钮，方便想在会话开始前退出的学员使用。

{% code title="SessionLoadingOverlay.cs" %}

```csharp
using Convai.Runtime.Core.Async;
using Convai.Runtime.Facades;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class SessionLoadingOverlay : MonoBehaviour
{
    [SerializeField] private GameObject _overlayRoot;
    [SerializeField] private Slider     _progressBar;
    [SerializeField] private TMP_Text   _statusLabel;
    [SerializeField] private Button     _cancelButton;

    private IConvaiOperation<RoomSession> _connectOp;

    public void StartConnect()
    {
        _overlayRoot.SetActive(true);
        _connectOp = ConvaiManager.ActiveManager.ConnectAsync(destroyCancellationToken);
        _cancelButton.onClick.AddListener(OnCancelClicked);
        StartCoroutine(TrackConnect());
    }

    private IEnumerator TrackConnect()
    {
        _statusLabel.text = "Connecting…";

        while (!_connectOp.IsCompleted)
        {
            _progressBar.value = _connectOp.Progress;
            yield return null;
        }

        _overlayRoot.SetActive(false);
        _cancelButton.onClick.RemoveListener(OnCancelClicked);

        if (_connectOp.HasError)
            _statusLabel.text = $"Failed: {_connectOp.Error.Message}";
        else if (!_connectOp.IsCanceled)
            _statusLabel.text = "Connected.";
    }

    private void OnCancelClicked() => _connectOp?.Cancel();
}
```

{% endcode %}

#### 示例 2 — 将流式传输的转录词元写入自定义日志控件

在一个企业入职培训模拟中，Convai 会逐个流式传输转录词元，并将其逐个追加到自定义日志控件中，从而产生打字机效果。

{% code title="StreamingTranscriptLog.cs" %}

```csharp
using Convai.Runtime.Facades;
using TMPro;
using UnityEngine;

public class StreamingTranscriptLog : MonoBehaviour
{
    [SerializeField] private TMP_Text _log;

    // 在新的角色回合开始时调用此方法
    public async void AttachToStream(IConvaiStream<string> tokenStream)
    {
        try
        {
            await using (tokenStream)
            {
                await foreach (var token in tokenStream.ReadAllAsync(destroyCancellationToken))
                {
                    _log.text += token;
                }
            }
        }
        catch (System.OperationCanceledException)
        {
            // 流传输过程中组件被销毁——符合预期
        }
    }
}
```

{% endcode %}

***

### 故障排查

| 症状                                                      | 可能原因                                                                | 解决方法                                                                                         |
| ------------------------------------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| 操作会一直处于 `Running` 状态                                    | SDK 方法一直在等待永远不会到来的响应（网络超时）                                          | 设置一个带超时的 `CancellationToken` ： `new CancellationTokenSource(TimeSpan.FromSeconds(15)).Token` |
| `HasError` 为 `true` ，但 `ConvaiOperationException` 不会被抛出 | 使用协程路径时，错误会通过 `onError` 回调传递，而不是抛出                                  | 为 `onError` 添加回调，并传递给 `ToCoroutine()`                                                        |
| `catch (ConvaiOperationException)` 代码块在取消操作时永远不会执行      | 取消操作会抛出 `OperationCanceledException`，而不是 `ConvaiOperationException` | 另外添加一个 `catch (OperationCanceledException)` 代码块                                              |
| 调用 `operation.Cancel()`                                 | 后，取消操作不会产生任何效果                                                      | 调用 `IsCompleted` 后再调用 `Cancel()`                                                             |
| 场景卸载时流传输挂起                                              | `ReadAllAsync` 循环未传入 `CancellationToken`                            | 将 `destroyCancellationToken` 传递给 `ReadAllAsync`                                              |
| `ContinueWith` 选择器从未运行                                  | 源操作失败；错误会向上传播，选择器会被跳过                                               | 检查链式操作的 `HasError` 或捕获 `ConvaiOperationException` 在 await 调用处                                |

***

### 后续步骤

如需查看这些模式背后的完整类型参考，请参阅 [操作与流类型](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/operation-and-stream-types.md)。对于返回 `IConvaiOperation<T>`的 SDK 方法，请参阅 [ConvaiManager API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/convaimanager-api.md) 和 [角色与玩家 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/character-and-player-api.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/async-patterns.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
