1# Sendable对象冻结 2<!--Kit: ArkTS--> 3<!--Subsystem: CommonLibrary--> 4<!--Owner: @lijiamin2025--> 5<!--Designer: @weng-changcheng--> 6<!--Tester: @kirl75; @zsw_zhushiwei--> 7<!--Adviser: @ge-yafang--> 8 9Sendable对象支持冻结操作。冻结后,对象变为只读,不能修改属性。因此,多个并发实例间访问时无需加锁。可以通过调用[Object.freeze](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)接口冻结对象。 10 11> **说明:** 12> 13> 不支持在.ets文件中使用Object.freeze接口。 14 15## 使用示例 16 171. 提供ts文件封装Object.freeze方法。 18 19 ```ts 20 // helper.ts 21 export function freezeObj(obj: any) { 22 Object.freeze(obj); 23 } 24 ``` 25 <!-- @[provide_encapsulate_method](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/managers/helper.ts) --> 26 272. 调用freeze方法冻结对象,然后将其发送到子线程。 28 29 ```ts 30 // Index.ets 31 import { freezeObj } from './helper'; 32 import { worker } from '@kit.ArkTS'; 33 34 @Sendable 35 export class GlobalConfig { 36 // 一些配置属性与方法 37 init() { 38 // 初始化相关逻辑 39 freezeObj(this); // 初始化完成后冻结当前对象 40 } 41 } 42 43 @Entry 44 @Component 45 struct Index { 46 build() { 47 Column() { 48 Text("Sendable freezeObj Test") 49 .id('HelloWorld') 50 .fontSize(50) 51 .fontWeight(FontWeight.Bold) 52 .onClick(() => { 53 let gConfig = new GlobalConfig(); 54 gConfig.init(); 55 const workerInstance = new worker.ThreadWorker('entry/ets/workers/Worker.ets', { name: "Worker1" }); 56 workerInstance.postMessage(gConfig); 57 }) 58 } 59 .height('100%') 60 .width('100%') 61 } 62 } 63 ``` 64 <!-- @[freeze_obj_send_child_thread](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/managers/SendableFreeze.ets) --> 65 663. 子线程直接操作对象,不加锁。 67 68 ```ts 69 // Worker.ets 70 import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS'; 71 import { GlobalConfig } from '../pages/Index'; 72 73 const workerPort: ThreadWorkerGlobalScope = worker.workerPort; 74 workerPort.onmessage = (e: MessageEvents) => { 75 let gConfig: GlobalConfig = e.data; 76 // 使用gConfig对象 77 } 78 ``` 79 <!-- @[directly_operate_obj](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/workers/Worker.ets) --> 80