harmony 鸿蒙Freezing Sendable Objects
Freezing Sendable Objects
Sendable objects can be frozen, making them read-only and preventing any additions, deletions, or modifications to their properties. Once frozen, these objects can be safely accessed across multiple concurrent instances without the need for locks. This is achieved using the Object.freeze method.
Usage Example
- Encapsulate the Object.freeze method in a TS file.
// helper.ts
export function freezeObj(obj: any) {
Object.freeze(obj);
}
- Call the freeze method to freeze an object and send it to a child thread.
// Index.ets
import { freezeObj } from './helper';
import { worker } from '@kit.ArkTS';
@Sendable
export class GlobalConfig {
// Configuration properties and methods
init() {
// Initialization logic
freezeObj(this) // Freeze the object after the initialization is complete.
}
}
@Entry
@Component
struct Index {
build() {
Column() {
Text("Sendable freezeObj Test")
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let gConifg = new GlobalConfig();
gConifg.init();
const workerInstance = new worker.ThreadWorker('entry/ets/workers/Worker.ets', { name: "Worker1" });
workerInstance.postMessage(gConifg);
})
}
.height('100%')
.width('100%')
}
}
- Perform operations on the frozen object directly in the child thread without locking.
// Worker.ets
import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
import { GlobalConfig } from '../pages/Index';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
workerPort.onmessage = (e: MessageEvents) => {
let gConfig: GlobalConfig = e.data;
// Use the gConfig object.
}
你可能感兴趣的鸿蒙文章
harmony 鸿蒙Configuring arkOptions in build-profile.json5
harmony 鸿蒙Ark Bytecode File Format
harmony 鸿蒙Naming Conventions for Ark Bytecode Functions
harmony 鸿蒙Ark Bytecode Fundamentals
harmony 鸿蒙Overview of Ark Bytecode
0
赞
- 所属分类: 后端技术
- 本文标签:
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦