> 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/operation-and-stream-types.md).

# 操作与流类型

大多数执行异步工作的 SDK 方法会返回 `IConvaiOperation<T>` 而不是 `Task<T>`。生成连续值序列的方法会返回 `IConvaiStream<T>`。这些类型旨在兼容 Unity 的协程系统、C# async/await 以及基于进度的流程——而无需强制依赖 `Task` 贯穿整个代码库。有关使用模式和代码示例，请参阅 [异步模式](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/async-patterns.md).

***

### 为什么使用自定义异步类型？

| 要求         | `Task<T>`              | `IConvaiOperation<T>`               |
| ---------- | ---------------------- | ----------------------------------- |
| 可在协程中使用    | 没有                     | 可以—— `ToCoroutine()`                |
| 无需异常的类型化错误 | 没有                     | 可以—— `错误` 属性                        |
| 进度报告       | 没有                     | 可以—— `进度` 属性                        |
| 直接 `await` | 是                      | 可以—— `GetAwaiter()`                 |
| 取消         | 通过 `CancellationToken` | 通过 `CancellationToken` + `Cancel()` |

***

### `IConvaiOperation<T>`

任何 SDK 异步操作的结果句柄。由以下方法返回 `ConnectAsync`, `DisconnectAsync`, `StartListeningAsync`, `WaitForCharacterReadyAsync`，以及其他方法。

#### 状态属性

| 属性             | 类型                | 说明                                                          |
| -------------- | ----------------- | ----------------------------------------------------------- |
| `Status`       | `OperationStatus` | 操作的当前生命周期状态                                                 |
| `IsCompleted`  | `bool`            | 当状态为以下值时为 True： `成功`, `故障`，或 `Canceled`                     |
| `IsSuccessful` | `bool`            | 当状态为以下值时为 True： `成功`                                        |
| `IsCanceled`   | `bool`            | 当状态为以下值时为 True： `Canceled`                                  |
| `HasError`     | `bool`            | 当状态为以下值时为 True： `故障`                                        |
| `错误`           | `ConvaiError`     | 在以下情况下填充： `HasError` 为 true；在成功或等待中时为默认值                    |
| `进度`           | `float`           | 完成度估计，范围为 0.0–1.0。并非所有操作都会报告细粒度进度——请检查 `Status` 以确认是否已最终完成。 |

#### Async/await

| 成员             | 说明                                                                            |
| -------------- | ----------------------------------------------------------------------------- |
| `GetAwaiter()` | 返回一个 `TaskAwaiter<T>`。可使 `直接 await 该操作` 。并在失败时抛出 `ConvaiOperationException` 。 |
| `AsTask()`     | 返回底层的 `Task<T>`。当需要传递给基于 Task 的 API 时使用，例如 `Task.WhenAll`.                    |

#### 协程

| 成员                                                                            | 说明                                                                                            |
| ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `ToCoroutine(Action<T> onSuccess = null, Action<ConvaiError> onError = null)` | 返回一个 `IEnumerator`。传递给 `StartCoroutine()`. `onSuccess` 接收结果； `onError` 如果操作失败，则接收错误。两个回调均为可选。 |

#### 链式调用

| 成员                                                   | 说明                                                          |
| ---------------------------------------------------- | ----------------------------------------------------------- |
| `ContinueWith<TNext>(Func<T, TNext> selector)`       | 同步转换。返回一个新的 `IConvaiOperation<TNext>` 其解析结果为 selector 的返回值。 |
| `ContinueWith<TNext>(Func<T, Task<TNext>> selector)` | 异步转换。返回一个新的 `IConvaiOperation<TNext>` 其在 selector 任务完成时解析。  |

`ContinueWith` 会传播错误——如果源操作失败，链式操作也会以相同错误失败，而不会调用 selector。

#### 取消

| 成员         | 说明                                       |
| ---------- | ---------------------------------------- |
| `Cancel()` | 请求协作式取消。操作将转换为 `Canceled` ，当 SDK 确认该请求时。 |

***

### `OperationStatus` enum

| 值              | 说明               |
| -------------- | ---------------- |
| `已创建` (0)      | 操作已创建但尚未开始       |
| `运行中` (1)      | 操作正在执行           |
| `成功` (2)       | 操作已成功完成。结果可用。    |
| `故障` (3)       | 操作失败。 `错误` 会被填充。 |
| `Canceled` (4) | 操作在完成前已取消        |

**生命周期：** `已创建 → 运行中 → 成功 / 故障 / 已取消`

***

### `ConvaiError` struct

携带结构化错误信息，无需异常处理即可使用。填充于 `IConvaiOperation<T>.Error` 当 `HasError` 为 true 时。

| 成员          | 类型          | 说明                                  |
| ----------- | ----------- | ----------------------------------- |
| `代码`        | `string`    | 机器可读的错误代码，例如 `"connection.timeout"` |
| `消息`        | `string`    | 人类可读的描述                             |
| `Exception` | `Exception` | 底层异常，如果错误源自某个异常。可能为 `null`.         |
| `IsEmpty`   | `bool`      | 当这是默认值（无错误）时为 True                  |

#### 静态工厂方法

```csharp
ConvaiError.FromException(Exception exception, string code = "exception")
```

创建一个 `ConvaiError` 由异常生成的错误。用于从捕获的异常构造错误的自定义错误路径中。

`ConvaiError` 是一个 struct，并支持 `Equals`, `GetHashCode`，以及 `ToString()`.

***

### `ConvaiOperationException`

当你 `await` 对一个 `IConvaiOperation<T>` 已失败的对象进行操作时抛出。继承自 `Exception`.

| 属性   | 类型       | 说明                                                |
| ---- | -------- | ------------------------------------------------- |
| `代码` | `string` | 底层的错误代码，来自 `ConvaiError` ——对应于 `ConvaiError.Code` |
| `消息` | `string` | 继承而来——人类可读的描述                                     |

**`HasError` 与抛出异常相比：**

* **协程** (`ToCoroutine`）：错误会传递给 `onError` 回调。不会抛出异常。
* **Async/await**：失败的操作会抛出 `ConvaiOperationException`。使用以下方式捕获它： `try/catch`.
* `HasError` 为 `true` 在这两种情况下都适用——无论采用何种消费模式，你都可以随时轮询它。

{% hint style="warning" %}
使用 async/await 时， **取消会抛出 `OperationCanceledException`**，而不是 `ConvaiOperationException`。务必同时捕获这两种异常：

```csharp
try
{
    await manager.ConnectAsync(destroyCancellationToken);
}
catch (ConvaiOperationException ex) { /* SDK 错误 */ }
catch (OperationCanceledException)  { /* 已取消   */ }
```

{% endhint %}

***

### `IConvaiStream<T>`

由随时间生成连续值序列的方法返回，例如流式转写 token 或流式音频帧。实现 `IAsyncDisposable`.

#### 属性

| 属性       | 类型             | 说明                        |
| -------- | -------------- | ------------------------- |
| `Status` | `StreamStatus` | 流的当前生命周期状态                |
| `错误`     | `ConvaiError`  | 在以下情况下填充： `Status` 为 `故障` |

#### 方法

| 方法                                             | 返回                    | 说明                                 |
| ---------------------------------------------- | --------------------- | ---------------------------------- |
| `ReadAllAsync(CancellationToken ct = default)` | `IAsyncEnumerable<T>` | 按到达顺序产出项目。流结束时完成。支持取消。             |
| `DisposeAsync()`                               | `ValueTask`           | 释放流并释放资源。务必通过以下方式调用 `await using`. |

```csharp
await using var stream = GetSomeStream();
await foreach (var item in stream.ReadAllAsync(destroyCancellationToken))
{
    ProcessItem(item);
}
```

***

### `StreamStatus` enum

| 值              | 说明                |
| -------------- | ----------------- |
| `已创建` (0)      | 流已创建，但尚未开始流式传输    |
| `流式传输` (1)     | 流正在主动产出项目         |
| `已完成` (2)      | 所有项目都已送达；流已正常结束   |
| `故障` (3)       | 流遇到错误。 `错误` 会被填充。 |
| `Canceled` (4) | 流在完成前已取消          |

**生命周期：** `已创建 → 流式传输中 → 已完成 / 故障 / 已取消`

***

### `Unit` struct

```csharp
Unit.Value // 唯一实例
```

当操作没有有意义的返回值时，用作类型参数的 void 等价类型。诸如以下操作： `DisconnectAsync()` 是位于 `StopListeningAsync()` 返回 `IConvaiOperation<Unit>` — `await` 使用它们是为了副作用，而不是结果。

`Unit` 支持相等性（`==`, `!=`, `Equals`）以及 `ToString()` 返回 `"()"`.

***

### 下一步

有关使用这些类型的实用消费模式，请参阅 [异步模式](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/async-patterns.md)。对于所有返回以下类型的方法，请参阅 `IConvaiOperation<T>`，请参阅 [ConvaiManager API](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/convaimanager-api.md) 是位于 [Character & Player API](/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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/operation-and-stream-types.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
