• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Real-Time Communication Between the Worker Thread and Host Thread
2
3
4In ArkTS, Worker differ from TaskPool in that it has a limited number of threads but can run for extended periods. A [Worker](worker-introduction.md) can execute multiple tasks, each with varying execution times and results. The host thread needs to call different methods in the Worker based on the situation, and the Worker must promptly return the results to the host thread.
5
6
7The following example demonstrates how a Worker can respond to a "hello world" request.
8
9
101. Create a Worker that executes tasks.
11
12   ```ts
13   // Worker.ets
14   import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
15
16   const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
17   // The Worker receives messages from the host thread and processes them accordingly.
18   workerPort.onmessage = (e: MessageEvents): void => {
19     if (e.data === 'hello world') {
20       workerPort.postMessage('success');
21     }
22   }
23   ```
24   <!-- @[create_worker_execute_multi_task](https://gitee.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationScenario/entry/src/main/ets/workers/Worker.ets) -->
25
262. In the host thread (UI main thread), create a Worker object. Use the **postMessage** method to send a message to the Worker thread when a button is clicked, and use the **onmessage** method of Worker to receive the response.
27
28   ```ts
29   // Index.ets
30   import { worker } from '@kit.ArkTS';
31   import { BusinessError } from '@kit.BasicServicesKit';
32
33   function promiseCase() {
34     let p: Promise<void> = new Promise<void>((resolve: Function, reject: Function) => {
35       setTimeout(() => {
36         resolve(1);
37       }, 100)
38     }).then(undefined, (error: BusinessError) => {
39     })
40     return p;
41   }
42
43   async function postMessageTest() {
44     let ss = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
45     let res = undefined;
46     let flag = false;
47     let isTerminate = false;
48     ss.onexit = () => {
49       isTerminate = true;
50     }
51     // Receive messages sent by the Worker thread.
52     ss.onmessage = (e) => {
53       res = e.data;
54       flag = true;
55       console.info("worker:: res is  " + res);
56     }
57     // Send a message to the Worker thread.
58     ss.postMessage("hello world");
59     while (!flag) {
60       await promiseCase();
61     }
62
63     ss.terminate();
64     while (!isTerminate) {
65       await promiseCase();
66     }
67   }
68
69   @Entry
70   @Component
71   struct Index {
72     @State message: string = 'Hello World';
73     build() {
74       Row() {
75         Column() {
76           Text(this.message)
77             .fontSize(50)
78             .fontWeight(FontWeight.Bold)
79             .onClick(() => {
80               postMessageTest();
81             })
82         }
83         .width('100%')
84       }
85       .height('100%')
86     }
87   }
88   ```
89   <!-- @[respond_worker_instant_message](https://gitee.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationScenario/entry/src/main/ets/managers/WorkerCommunicatesWithMainthread.ets) -->
90
91
92In this example, the Worker thread receives a message from the host thread, processes it, and sends a response back. This enables real-time communication between the host thread and the Worker thread, allowing the host thread to conveniently use the execution results of the Worker.
93