1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16// [Start respond_worker_instant_message] 17import { worker } from '@kit.ArkTS'; 18import { BusinessError } from '@kit.BasicServicesKit'; 19 20function promiseCase() { 21 let p: Promise<void> = new Promise<void>((resolve: Function, reject: Function) => { 22 setTimeout(() => { 23 resolve(1); 24 }, 100) 25 }).then(undefined, (error: BusinessError) => { 26 }) 27 return p; 28} 29 30async function postMessageTest() { 31 let ss = new worker.ThreadWorker('entry/ets/workers/Worker.ets'); 32 let res = undefined; 33 let flag = false; 34 let isTerminate = false; 35 ss.onexit = () => { 36 isTerminate = true; 37 } 38 // 接收Worker线程发送的消息 39 ss.onmessage = (e) => { 40 res = e.data; 41 flag = true; 42 console.info('worker:: res is ' + res); 43 } 44 // 给Worker线程发送消息 45 ss.postMessage('hello world'); 46 while (!flag) { 47 await promiseCase(); 48 } 49 50 ss.terminate(); 51 while (!isTerminate) { 52 await promiseCase(); 53 } 54} 55 56@Entry 57@Component 58struct Index { 59 @State message: string = 'Hello World'; 60 61 build() { 62 Row() { 63 Column() { 64 Text(this.message) 65 .fontSize(50) 66 .fontWeight(FontWeight.Bold) 67 .onClick(() => { 68 postMessageTest(); 69 this.message = 'success'; 70 }) 71 } 72 .width('100%') 73 } 74 .height('100%') 75 } 76} 77// [End respond_worker_instant_message] 78