• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
16import { worker } from '@kit.ArkTS';
17import { BusinessError } from '@kit.BasicServicesKit';
18
19function promiseCase() {
20  let p: Promise<void> = new Promise<void>((resolve: Function, reject: Function) => {
21    setTimeout(() => {
22      resolve(1);
23    }, 100)
24  }).then(undefined, (error: BusinessError) => {
25  })
26  return p;
27}
28
29async function postMessageTest() {
30  let ss = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
31  let res = undefined;
32  let flag = false;
33  let isTerminate = false;
34  ss.onexit = () => {
35    isTerminate = true;
36  }
37  // 接收Worker线程发送的消息
38  ss.onmessage = (e) => {
39    res = e.data;
40    flag = true;
41    console.info('worker:: res is  ' + res);
42  }
43  // 给Worker线程发送消息
44  ss.postMessage('hello world');
45  while (!flag) {
46    await promiseCase();
47  }
48
49  ss.terminate();
50  while (!isTerminate) {
51    await promiseCase();
52  }
53}
54
55@Entry
56@Component
57struct Index {
58  @State message: string = 'Hello World';
59
60  build() {
61    Row() {
62      Column() {
63        Text(this.message)
64          .fontSize(50)
65          .fontWeight(FontWeight.Bold)
66          .onClick(() => {
67            postMessageTest();
68            this.message = 'success';
69          })
70      }
71      .width('100%')
72    }
73    .height('100%')
74  }
75}
76