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 对象所有字段也必须是 SendableSendable export class CatData { id: string ; level: number 1; x: number 0; y: number 0; }三、taskpool 中的 SendableConcurrent 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 序列化特性SendableJSON 序列化性能高零拷贝低字符串转换类型安全✅❌as断言使用方法直接传对象stringify/parse适用场景频繁线程通信一次性的数据传递五、最佳实践频繁传递的数据用 Sendable游戏帧数据字段必须初始化number 0、string 保持简单Sendable 类不要有复杂方法总结Sendable标记可跨线程共享的类零拷贝传递数据。核心要点Sendable装饰类、 字段必须有初始值、 taskpool 中直接传递。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Sendable 文档第 145 篇Worker第 147 篇taskpool-execute第 148 篇task-group