HarmonyOS应用开发实战:猫猫大作战-sendable 共享数据
·


前言
@Sendable 是 ArkTS 中标记可跨线程传递数据的装饰器。与普通对象不同,@Sendable 对象可以通过 taskpool 或 Worker 在线程间共享。
一、@Sendable 基础
@Sendable
export class GameResult {
score: number = 0;
duration: number = 0;
maxLevel: number = 0;
constructor(score: number, duration: number, maxLevel: number) {
this.score = score;
this.duration = duration;
this.maxLevel = maxLevel;
}
}
@Concurrent
function processResult(result: GameResult): number {
return result.score * result.duration;
}
二、Sendable 约束
| 约束 | 说明 |
|---|---|
| @Sendable 装饰 | 类必须标记 |
| 字段必须初始化 | score: number = 0 |
| 只支持基本类型 | number、string、boolean |
| 方法只能同步 | 不能包含异步方法 |
| 不能引用非 Sendable 对象 | 所有字段也必须是 Sendable |
@Sendable
export class CatData {
id: string = '';
level: number = 1;
x: number = 0;
y: number = 0;
}
三、taskpool 中的 Sendable
@Concurrent
function saveResult(result: GameResult): boolean {
// 在后台线程处理 @Sendable 数据
console.info(`得分: ${result.score}, 时长: ${result.duration}`);
return true;
}
async function onGameEnd(score: number, duration: number) {
const result = new GameResult(score, duration, this.maxLevel);
await taskpool.execute(saveResult, result);
}
四、@Sendable vs 序列化
| 特性 | @Sendable | JSON 序列化 |
|---|---|---|
| 性能 | 高(零拷贝) | 低(字符串转换) |
| 类型安全 | ✅ | ❌ as 断言 |
| 使用方法 | 直接传对象 | stringify/parse |
| 适用场景 | 频繁线程通信 | 一次性的数据传递 |
五、最佳实践
- 频繁传递的数据用 @Sendable:游戏帧数据
- 字段必须初始化:
number = 0、string = '' - 保持简单:Sendable 类不要有复杂方法
总结
@Sendable 标记可跨线程共享的类,零拷贝传递数据。核心要点:@Sendable 装饰类、 字段必须有初始值、 taskpool 中直接传递。
如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!
相关资源:
更多推荐


所有评论(0)