openharmony 鸿蒙 container-object

2026-08-25 浏览 (1)

Container Object

Container objects can be serialized to ensure content consistency between threads, enabling inter-thread data transfer.

Currently, the TreeSet object supports serialization.

NOTE

  • Since OpenHarmony 6.1, TreeSet can be used for cross-thread data transfer.

  • When passing container objects across threads, only data can be transmitted, and custom methods will be lost. If custom methods are required, you need to mark them as Sendable functions using the @Sendable decorator, after which the custom methods can be passed across threads.

Example

import { taskpool, TreeSet } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';

@Sendable
function sendableCompareFunc(firstValue: number, secondValue: number): boolean {
    return firstValue > secondValue;
}

@Concurrent
function treeSetTestFunc(treeSet: TreeSet<number>) {
  for (let value of treeSet) {
    console.info('value:', value);
  }
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          // 1. Create a test instance objA.
          let treeSet: TreeSet<number> = new TreeSet<number>(sendableCompareFunc);

          treeSet.add(1);
          treeSet.add(5);
          treeSet.add(3);
          treeSet.add(2);
          // 2. Create a task and transfer treeSet to the task. The task is transferred to the child thread through serialization.
          let task = new taskpool.Task(treeSetTestFunc, treeSet);
          // 3. Execute the task.
          taskpool.execute(task).then(() => {
            console.info('taskpool: execute task success!');
          }).catch((e: BusinessError) => {
            console.error(`taskpool: execute task: Code: ${e.code}, message: ${e.message}`);
          })
          this.message = 'success';
        })
    }
    .height('100%')
    .width('100%')
  }
}

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 multi-thread-concurrency-overview

openharmony 鸿蒙 arkts-condition-variable-introduction

openharmony 鸿蒙 long-time-task-overview

openharmony 鸿蒙 batch-database-operations-guide

openharmony 鸿蒙 bytecode-obfuscation-guide

openharmony 鸿蒙 bytecode-obfuscation-questions

openharmony 鸿蒙 napi-define-sendable-object

openharmony 鸿蒙 arkts-lazy-import

openharmony 鸿蒙 independent-time-consuming-task

openharmony 鸿蒙 concurrency-overview

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/agLcdBjz