1# @ohos.worker (Starting the Worker)
2
3The Worker thread is an independent thread running in parallel with the main thread. The thread that creates the Worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the Worker thread. The Worker thread can process time-consuming operations, but cannot directly operate the UI.
4
5With the Worker module, you can provide a multithreaded environment for an application, so that the application can perform a time-consuming operation in a background thread. This greatly prevents a computing-intensive or high-latency task from blocking the running of the host thread. A Worker instance will not be proactively destroyed once it is created. It consumes resources to keep running. Therefore, you should call the API to terminate it in a timely manner.
6
7The Context object of the Worker thread is different from that of the UI main thread. The Worker thread does not support UI operations.
8
9For details about the precautions for using Worker, see [Precautions for Worker](../../arkts-utils/worker-introduction.md#precautions-for-worker).
10
11> **NOTE**
12>
13> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
14
15## Modules to Import
16
17```ts
18import { worker } from '@kit.ArkTS';
19```
20
21
22## Attributes
23
24**System capability**: SystemCapability.Utils.Lang
25
26| Name                             | Type                                                        | Readable| Writable| Description                                                        |
27| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
28| workerPort<sup>9+</sup>           | [ThreadWorkerGlobalScope](#threadworkerglobalscope9)         | Yes  | Yes  | Object of the Worker thread used to communicate with the host thread. **Atomic service API**: This API can be used in atomic services since API version 11.                        |
29| parentPort<sup>(deprecated)</sup> | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes  | Yes  | Object of the Worker thread used to communicate with the host thread.<br>This attribute is supported since API version 7 and deprecated since API version 9.<br>You are advised to use **workerPort<sup>9+</sup>** instead.|
30
31
32## WorkerOptions
33
34Provides options that can be set for the Worker instance to create.
35
36**System capability**: SystemCapability.Utils.Lang
37
38| Name| Type| Read-only| Optional| Description|
39| ---- | -------- | ---- | ---- | -------------- |
40| type | 'classic' \| 'module' | Yes  | Yes| Mode in which the Worker instance executes the script. The **module** type is not supported yet. The default value is **classic**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
41| name | string   | Yes  | Yes| Name of the Worker thread. The default value is **undefined**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
42| shared | boolean | Yes  | Yes| Whether sharing of the Worker instance is enabled. Currently, sharing is not supported.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
43
44## ThreadWorker<sup>9+</sup>
45
46Before using the following APIs, you must create a ThreadWorker instance. The ThreadWorker class inherits from [WorkerEventTarget](#workereventtarget9).
47
48### constructor<sup>9+</sup>
49
50constructor(scriptURL: string, options?: WorkerOptions)
51
52A constructor used to create a ThreadWorker instance.
53
54**Atomic service API**: This API can be used in atomic services since API version 11.
55
56**System capability**: SystemCapability.Utils.Lang
57
58**Parameters**
59
60| Name   | Type                           | Mandatory| Description                                                        |
61| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
62| scriptURL | string                          | Yes  | URL of the Worker thread file.<br>For details about the rules, see [Precautions for File URLs](../../arkts-utils/worker-introduction.md#precautions-for-file-urls).|
63| options   | [WorkerOptions](#workeroptions) | No  | Options that can be set for the Worker instance.                                          |
64
65**Error codes**
66
67For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
68
69| ID| Error Message|
70| -------- | -------- |
71| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
72| 10200003 | Worker initialization failed. |
73| 10200007 | The worker file path is invalid. |
74
75**Example**
76
77The following code snippet shows how to load the Worker thread file of the ability in the stage model. For details about how to use the library to load the Worker thread file, see [Precautions for File URLs](../../arkts-utils/worker-introduction.md#precautions-for-file-urls).
78
79```ts
80import { worker } from '@kit.ArkTS';
81
82// Two scenarios are involved.
83
84// Scenario 1: URL of the Worker thread file: "entry/src/main/ets/workers/worker.ets"
85const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ets', {name:"first worker in Stage model"});
86
87// Scenario 2: URL of the Worker thread file: "phone/src/main/ets/ThreadFile/workers/worker.ets"
88const workerStageModel02 = new worker.ThreadWorker('phone/ets/ThreadFile/workers/worker.ets');
89```
90
91
92### postMessage<sup>9+</sup>
93
94postMessage(message: Object, transfer: ArrayBuffer[]): void
95
96Sends a message from the host thread to the Worker thread by transferring object ownership.
97
98**System capability**: SystemCapability.Utils.Lang
99
100**Atomic service API**: This API can be used in atomic services since API version 11.
101
102**Parameters**
103
104| Name  | Type         | Mandatory| Description                                                        |
105| -------- | ------------- | ---- | ------------------------------------------------------------ |
106| message  | Object        | Yes  | Data to be sent to the Worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
107| transfer | ArrayBuffer[] | Yes  | ArrayBuffer instance holding an array of objects for which the ownership is transferred to the Worker thread. After the transfer, the objects are available only in the Worker thread. The array cannot be null.|
108
109**Error codes**
110
111For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
112
113| ID| Error Message                               |
114| -------- | ----------------------------------------- |
115| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
116| 10200004 | The Worker instance is not running.           |
117| 10200006 | An exception occurred during serialization. |
118
119**Example**
120
121```ts
122// Worker.ets
123import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
124
125// Create an object in the Worker thread for communicating with the host thread.
126const workerPort = worker.workerPort
127
128// The Worker thread receives information from the host thread.
129workerPort.onmessage = (e: MessageEvents): void => {
130  // data carries the information sent by the host thread.
131  let data: number = e.data;
132  // Write data to the received buffer.
133  const view = new Int8Array(data).fill(3);
134  // The Worker thread sends information to the host thread.
135  workerPort.postMessage(view);
136}
137
138// Trigger a callback when an error occurs in the Worker thread.
139workerPort.onerror = (err: ErrorEvent) => {
140  console.log("worker.ets onerror" + err.message);
141}
142```
143```ts
144// Index.ets
145import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
146
147@Entry
148@Component
149struct Index {
150  @State message: string = 'Hello World';
151
152  build() {
153    Row() {
154      Column() {
155        Text(this.message)
156          .fontSize(50)
157          .fontWeight(FontWeight.Bold)
158          .onClick(() => {
159            // Create a Worker instance in the host thread.
160            const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
161            // The host thread transfers information to the Worker thread.
162            const buffer = new ArrayBuffer(8);
163            workerInstance.postMessage(buffer, [buffer]);
164            // The host thread receives information from the Worker thread.
165            workerInstance.onmessage = (e: MessageEvents): void => {
166              // data carries the information sent by the Worker thread.
167              let data: number = e.data;
168              console.info("main thread data is  " + data);
169              // Terminate the Worker instance.
170              workerInstance.terminate();
171            }
172            // Call onexit().
173            workerInstance.onexit = (code) => {
174              console.log("main thread terminate");
175            }
176
177            workerInstance.onerror = (err: ErrorEvent) => {
178              console.log("main error message " + err.message);
179            }
180          })
181      }
182      .width('100%')
183      .height('100%')
184    }
185  }
186}
187```
188
189### postMessage<sup>9+</sup>
190
191postMessage(message: Object, options?: PostMessageOptions): void
192
193Sends a message from the host thread to the Worker thread by transferring object ownership or copying data.
194
195**Atomic service API**: This API can be used in atomic services since API version 11.
196
197**System capability**: SystemCapability.Utils.Lang
198
199**Parameters**
200
201| Name | Type                                     | Mandatory| Description                                                        |
202| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
203| message | Object                                    | Yes  | Data to be sent to the Worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
204| options | [PostMessageOptions](#postmessageoptions) | No  | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the Worker thread and becomes unavailable in the host thread. The objects are available only in the Worker thread.<br>If this parameter is not specified, the default value **undefined** is used, and information is transferred to the Worker thread by copying data.|
205
206**Error codes**
207
208For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
209
210| ID| Error Message                               |
211| -------- | ----------------------------------------- |
212| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
213| 10200004 | The Worker instance is not running.           |
214| 10200006 | An exception occurred during serialization. |
215
216**Example**
217
218```ts
219const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
220
221workerInstance.postMessage("hello world");
222
223let buffer = new ArrayBuffer(8);
224workerInstance.postMessage(buffer, [buffer]);
225```
226
227
228### postMessageWithSharedSendable<sup>12+</sup>
229
230postMessageWithSharedSendable(message: Object, transfer?: ArrayBuffer[]): void
231
232Sends a message from the host thread to the Worker thread. In the message, a sendable object is passed by reference, and a non-sendable object is passed by serialization.
233
234**Atomic service API**: This API can be used in atomic services since API version 12.
235
236**System capability**: SystemCapability.Utils.Lang
237
238**Parameters**
239
240| Name | Type                                     | Mandatory| Description                                                        |
241| --------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
242| message   | Object	     | Yes  | Data to be sent to the Worker thread. The data object must be sequenceable or sendable. For details about the supported sequenceable types, see [Sequenceable Data Types](#sequenceable-data-types). For details about the supported sendable types, see [Sendable Data Types](../../arkts-utils/arkts-sendable.md#sendable-data-types).|
243| transfer  | ArrayBuffer[] | No  | ArrayBuffer instance holding an array of objects for which the ownership is transferred to the Worker thread. After the transfer, the objects are available only in the Worker thread. The array cannot be null. The default value is an empty array.|
244
245**Error codes**
246
247For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
248
249| ID| Error Message                               |
250| -------- | ----------------------------------------- |
251| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
252| 10200004 | The Worker instance is not running.           |
253| 10200006 | An exception occurred during serialization. |
254
255**Example**
256
257<!--code_no_check-->
258```ts
259// index.ets
260// Create a SendableObject instance and pass it to the Worker thread through the host thread.
261
262import { worker } from '@kit.ArkTS';
263import { SendableObject } from './sendable'
264
265const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
266let object: SendableObject = new SendableObject();
267workerInstance.postMessageWithSharedSendable(object);
268```
269
270```ts
271// sendable.ets
272// Define SendableObject.
273
274@Sendable
275export class SendableObject {
276  a:number = 45;
277}
278```
279
280<!--code_no_check-->
281```ts
282// The worker file path is entry/src/main/ets/workers/Worker.ets.
283// Worker.ets
284// Receive and access the data passed from the host thread to the Worker thread.
285
286import { SendableObject } from '../pages/sendable'
287import { worker, ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@kit.ArkTS';
288
289const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
290workerPort.onmessage = (e: MessageEvents) => {
291  let obj: SendableObject = e.data;
292  console.info("sendable obj is: " + obj.a);
293}
294```
295
296
297### on<sup>9+</sup>
298
299on(type: string, listener: WorkerEventListener): void
300
301Adds an event listener for the Worker thread. This API provides the same functionality as [addEventListener<sup>9+</sup>](#addeventlistener9).
302
303**Atomic service API**: This API can be used in atomic services since API version 12.
304
305**System capability**: SystemCapability.Utils.Lang
306
307**Parameters**
308
309| Name  | Type                                        | Mandatory| Description                  |
310| -------- | -------------------------------------------- | ---- | ---------------------- |
311| type     | string                                       | Yes  | Type of the event to listen for.      |
312| listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs.|
313
314**Error codes**
315
316For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
317
318| ID| Error Message                                  |
319| -------- | -------------------------------------------- |
320| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
321| 10200004 | Worker instance is not running.              |
322| 10200005 | The invoked API is not supported in workers. |
323
324**Example**
325
326```ts
327const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
328workerInstance.on("alert", ()=>{
329    console.log("alert listener callback");
330})
331```
332
333
334### once<sup>9+</sup>
335
336once(type: string, listener: WorkerEventListener): void
337
338Adds an event listener for the Worker thread and removes the event listener after it is invoked once.
339
340**Atomic service API**: This API can be used in atomic services since API version 12.
341
342**System capability**: SystemCapability.Utils.Lang
343
344**Parameters**
345
346| Name  | Type                                        | Mandatory| Description                  |
347| -------- | -------------------------------------------- | ---- | ---------------------- |
348| type     | string                                       | Yes  | Type of the event to listen for.      |
349| listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs.|
350
351**Error codes**
352
353For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
354
355| ID| Error Message                                  |
356| -------- | -------------------------------------------- |
357| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
358| 10200004 | Worker instance is not running.              |
359| 10200005 | The invoked API is not supported in workers. |
360
361**Example**
362
363```ts
364const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
365workerInstance.once("alert", ()=>{
366    console.log("alert listener callback");
367})
368```
369
370
371### off<sup>9+</sup>
372
373off(type: string, listener?: WorkerEventListener): void
374
375Removes an event listener for the Worker thread. This API provides the same functionality as [removeEventListener<sup>9+</sup>](#removeeventlistener9).
376
377**Atomic service API**: This API can be used in atomic services since API version 12.
378
379**System capability**: SystemCapability.Utils.Lang
380
381**Parameters**
382
383| Name  | Type                                        | Mandatory| Description                        |
384| -------- | -------------------------------------------- | ---- | ---------------------------- |
385| type     | string                                       | Yes  | Type of the event for which the event listener is to be removed.        |
386| listener | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when the listener is removed.|
387
388**Error codes**
389
390For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
391
392| ID| Error Message                                  |
393| -------- | -------------------------------------------- |
394| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
395| 10200004 | Worker instance is not running.              |
396| 10200005 | The invoked API is not supported in workers. |
397
398**Example**
399
400```ts
401const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
402// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener.
403workerInstance.off("alert");
404```
405
406### registerGlobalCallObject<sup>11+</sup>
407
408registerGlobalCallObject(instanceName: string, globalCallObject: Object): void
409
410Registers an object with the ThreadWorker instance of the host thread. In this way, the methods of the object can be called in the Worker thread through [callGlobalCallObjectMethod](#callglobalcallobjectmethod11).
411
412**Atomic service API**: This API can be used in atomic services since API version 12.
413
414**System capability**: SystemCapability.Utils.Lang
415
416**Parameters**
417
418| Name  | Type         | Mandatory| Description                                                        |
419| -------- | ------------- | ---- | ------------------------------------------------------------ |
420| instanceName  | string        | Yes  | Key used for registration, based on which the registered object is identified during method calling.|
421| globalCallObject | Object | Yes  | Object to register. The ThreadWorker instance holds a strong reference to the object.|
422
423**Error codes**
424
425For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
426
427| ID| Error Message                               |
428| -------- | ----------------------------------------- |
429| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
430| 10200004 | Worker instance is not running.           |
431
432**Example**
433```ts
434const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
435class TestObj {
436  private message : string = "this is a message from TestObj"
437  public getMessage() : string {
438    return this.message;
439  }
440  public getMessageWithInput(str : string) : string {
441    return this.message + " with input: " + str;
442  }
443}
444let registerObj = new TestObj();
445// Register registerObj with the ThreadWorker instance.
446workerInstance.registerGlobalCallObject("myObj", registerObj);
447workerInstance.postMessage("start worker")
448```
449
450### unregisterGlobalCallObject<sup>11+</sup>
451
452unregisterGlobalCallObject(instanceName?: string): void
453
454Unregisters an object with the ThreadWorker instance of the host thread. This API releases the strong reference between the ThreadWorker instance and the target object. No error is reported if no object is matched.
455
456**Atomic service API**: This API can be used in atomic services since API version 12.
457
458**System capability**: SystemCapability.Utils.Lang
459
460**Parameters**
461
462| Name  | Type         | Mandatory| Description                                                        |
463| -------- | ------------- | ---- | ------------------------------------------------------------ |
464| instanceName  | string        | No  | Key used for registration. If this parameter is left blank, all registered objects registered in the ThreadWorker instance are unregistered.|
465
466**Error codes**
467
468For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
469
470| ID| Error Message                               |
471| -------- | ----------------------------------------- |
472| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
473| 10200004 | Worker instance is not running. |
474
475**Example**
476```ts
477const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
478class TestObj {
479  private message : string = "this is a message from TestObj"
480  public getMessage() : string {
481    return this.message;
482  }
483  public getMessageWithInput(str : string) : string {
484    return this.message + " with input: " + str;
485  }
486}
487let registerObj = new TestObj();
488workerInstance.registerGlobalCallObject("myObj", registerObj);
489// Unregister the object.
490workerInstance.unregisterGlobalCallObject("myObj");
491// Unregister all objects from the ThreadWorker instance.
492//workerInstance.unregisterGlobalCallObject();
493workerInstance.postMessage("start worker")
494```
495
496### terminate<sup>9+</sup>
497
498terminate(): void
499
500Terminates the Worker thread to stop it from receiving messages.
501
502**Atomic service API**: This API can be used in atomic services since API version 11.
503
504**System capability**: SystemCapability.Utils.Lang
505
506**Error codes**
507
508For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
509
510| ID| Error Message                     |
511| -------- | ------------------------------- |
512| 10200004 | The Worker instance is not running. |
513
514**Example**
515
516```ts
517const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
518workerInstance.terminate();
519```
520
521
522### onexit<sup>9+</sup>
523
524onexit?: (code: number) =&gt; void
525
526Called when the Worker thread exits. The event handler is executed in the host thread. In the callback function, the **code** value is of the number type, where the value **1** indicates abnormal exit and **0** indicates normal exit.
527
528**Atomic service API**: This API can be used in atomic services since API version 11.
529
530**System capability**: SystemCapability.Utils.Lang
531
532**Error codes**
533
534For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
535
536| ID| Error Message                                  |
537| -------- | -------------------------------------------- |
538| 401      | Parameter error. Possible causes: 1.Incorrect parameter types. |
539| 10200004 | The Worker instance is not running.              |
540| 10200005 | The called API is not supported in the worker thread. |
541
542**Example**
543
544```ts
545const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
546workerInstance.onexit = (code) => {
547 console.log("onexit");
548}
549
550// onexit is executed in either of the following ways:
551// Main thread
552workerInstance.terminate();
553
554// Worker thread
555//workerPort.close()
556```
557
558
559### onerror<sup>9+</sup>
560
561onerror?: (err: ErrorEvent) =&gt; void
562
563Called when an exception occurs during worker execution. The event handler is executed in the host thread. In the callback function, the **err** type is [ErrorEvent](#errorevent), indicating the received abnormal data.
564
565**Atomic service API**: This API can be used in atomic services since API version 11.
566
567**System capability**: SystemCapability.Utils.Lang
568
569**Error codes**
570
571For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
572
573| ID| Error Message                                  |
574| -------- | -------------------------------------------- |
575| 401      | Parameter error. Possible causes: 1.Incorrect parameter types. |
576| 10200004 | The Worker instance is not running.              |
577| 10200005 | The called API is not supported in the worker thread. |
578
579**Example**
580
581```ts
582import { worker, ErrorEvent } from '@kit.ArkTS';
583
584const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
585workerInstance.onerror = (err: ErrorEvent) => {
586  console.log("onerror" + err.message);
587}
588```
589
590
591### onmessage<sup>9+</sup>
592
593onmessage?: (event: MessageEvents) =&gt; void
594
595Called when the host thread receives a message sent by the Worker thread through **workerPort.postMessage**. The event handler is executed in the host thread. In the callback function, the **event** type is [MessageEvents](#messageevents9), indicating the received message data.
596
597**Atomic service API**: This API can be used in atomic services since API version 11.
598
599**System capability**: SystemCapability.Utils.Lang
600
601**Error codes**
602
603For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
604
605| ID| Error Message                                  |
606| -------- | -------------------------------------------- |
607| 401      | Parameter error. Possible causes: 1.Incorrect parameter types. |
608| 10200004 | The Worker instance is not running.              |
609| 10200005 | The called API is not supported in the worker thread. |
610
611**Example**
612
613```ts
614import { worker, MessageEvents } from '@kit.ArkTS';
615
616const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
617workerInstance.onmessage = (e: MessageEvents): void => {
618 // e: MessageEvents. The usage is as follows:
619 // let data = e.data;
620 console.log("onmessage");
621}
622```
623
624
625### onmessageerror<sup>9+</sup>
626
627onmessageerror?: (event: MessageEvents) =&gt; void
628
629Called when the Worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. In the callback function, the **event** type is [MessageEvents](#messageevents9), indicating the received message data.
630
631**Atomic service API**: This API can be used in atomic services since API version 11.
632
633**System capability**: SystemCapability.Utils.Lang
634
635**Error codes**
636
637For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
638
639| ID| Error Message                                  |
640| -------- | -------------------------------------------- |
641| 401      | Parameter error. Possible causes: 1.Incorrect parameter types. |
642| 10200004 | The Worker instance is not running.              |
643| 10200005 | The called API is not supported in the worker thread. |
644
645**Example**
646
647```ts
648import { worker, MessageEvents } from '@kit.ArkTS';
649
650const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
651workerInstance.onmessageerror = (err: MessageEvents) => {
652  console.log("onmessageerror");
653}
654```
655
656### addEventListener<sup>9+</sup>
657
658addEventListener(type: string, listener: WorkerEventListener): void
659
660Adds an event listener for the Worker thread. This API provides the same functionality as [on<sup>9+</sup>](#on9).
661
662**Atomic service API**: This API can be used in atomic services since API version 12.
663
664**System capability**: SystemCapability.Utils.Lang
665
666**Parameters**
667
668| Name  | Type                                        | Mandatory| Description            |
669| -------- | -------------------------------------------- | ---- | ---------------- |
670| type     | string                                       | Yes  | Type of the event to listen for.|
671| listener | [WorkerEventListener](#workereventlistener9) | Yes  | Callback to invoke when an event of the specified type occurs.    |
672
673**Error codes**
674
675For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
676
677| ID| Error Message                                  |
678| -------- | -------------------------------------------- |
679| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
680| 10200004 | Worker instance is not running.              |
681| 10200005 | The invoked API is not supported in workers. |
682
683**Example**
684
685```ts
686const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
687workerInstance.addEventListener("alert", ()=>{
688    console.log("alert listener callback");
689})
690```
691
692
693### removeEventListener<sup>9+</sup>
694
695removeEventListener(type: string, callback?: WorkerEventListener): void
696
697Removes an event listener for the Worker thread. This API provides the same functionality as [off<sup>9+</sup>](#off9).
698
699**Atomic service API**: This API can be used in atomic services since API version 12.
700
701**System capability**: SystemCapability.Utils.Lang
702
703**Parameters**
704
705| Name  | Type                                        | Mandatory| Description                        |
706| -------- | -------------------------------------------- | ---- | ---------------------------- |
707| type     | string                                       | Yes  | Type of the event for which the event listener is to be removed.    |
708| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when the listener is removed.|
709
710**Error codes**
711
712For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
713
714| ID| Error Message                     |
715| -------- | ------------------------------- |
716| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
717| 10200004 | Worker instance is not running. |
718
719**Example**
720
721```ts
722const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
723workerInstance.addEventListener("alert", ()=>{
724    console.log("alert listener callback");
725})
726workerInstance.removeEventListener("alert");
727```
728
729
730### dispatchEvent<sup>9+</sup>
731
732dispatchEvent(event: Event): boolean
733
734Dispatches the event defined for the Worker thread.
735
736**Atomic service API**: This API can be used in atomic services since API version 12.
737
738**System capability**: SystemCapability.Utils.Lang
739
740**Parameters**
741
742| Name| Type           | Mandatory| Description            |
743| ------ | --------------- | ---- | ---------------- |
744| event  | [Event](#event) | Yes  | Event to dispatch.|
745
746**Return value**
747
748| Type   | Description                           |
749| ------- | ------------------------------- |
750| boolean | Returns **true** if the event is dispatched; returns **false** otherwise.|
751
752**Error codes**
753
754For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
755
756| ID| Error Message                     |
757| -------- | ------------------------------- |
758| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
759| 10200004 | Worker instance is not running. |
760
761**Example**
762
763```ts
764const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
765
766workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet.
767```
768
769The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows:
770
771```ts
772import { worker, MessageEvents } from '@kit.ArkTS';
773
774const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
775
776// Usage 1:
777workerInstance.on("alert_on", ()=>{
778    console.log("alert listener callback");
779})
780workerInstance.once("alert_once", ()=>{
781    console.log("alert listener callback");
782})
783workerInstance.addEventListener("alert_add", ()=>{
784    console.log("alert listener callback");
785})
786
787// The event listener created by once is removed after being executed once.
788workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); // timeStamp is not supported yet.
789// The event listener created by on will not be proactively deleted.
790workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
791workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
792// The event listener created by addEventListener will not be proactively deleted.
793workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
794workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
795
796// Usage 2:
797// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
798// When type = "message", the event handler defined by onmessage will also be executed.
799// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
800// When type = "error", the event handler defined by onerror will also be executed.
801// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.
802
803workerInstance.addEventListener("message", ()=>{
804    console.log("message listener callback");
805})
806workerInstance.onmessage = (e: MessageEvents): void => {
807    console.log("onmessage : message listener callback");
808}
809// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
810workerInstance.dispatchEvent({type:"message", timeStamp:0});
811```
812
813
814### removeAllListener<sup>9+</sup>
815
816removeAllListener(): void
817
818Removes all event listeners for the Worker thread.
819
820**Atomic service API**: This API can be used in atomic services since API version 12.
821
822**System capability**: SystemCapability.Utils.Lang
823
824**Error codes**
825
826For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
827
828| ID| Error Message                     |
829| -------- | ------------------------------- |
830| 10200004 | Worker instance is not running. |
831
832**Example**
833
834```ts
835const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
836workerInstance.addEventListener("alert", ()=>{
837    console.log("alert listener callback");
838})
839workerInstance.removeAllListener();
840```
841
842## WorkerEventTarget<sup>9+</sup>
843
844Processes worker listening events.
845
846### addEventListener<sup>9+</sup>
847
848addEventListener(type: string, listener: WorkerEventListener): void
849
850Adds an event listener for the Worker thread. This API provides the same functionality as [on<sup>9+</sup>](#on9).
851
852**Atomic service API**: This API can be used in atomic services since API version 12.
853
854**System capability**: SystemCapability.Utils.Lang
855
856**Parameters**
857
858| Name  | Type                                        | Mandatory| Description            |
859| -------- | -------------------------------------------- | ---- | ---------------- |
860| type     | string                                       | Yes  | Type of the event to listen for.|
861| listener | [WorkerEventListener](#workereventlistener9) | Yes  | Callback to invoke when an event of the specified type occurs.    |
862
863**Error codes**
864
865For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
866
867| ID| Error Message                                  |
868| -------- | -------------------------------------------- |
869| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
870| 10200004 | The Worker instance is not running.              |
871| 10200005 | The called API is not supported in the worker thread. |
872
873**Example**
874
875```ts
876const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
877workerInstance.addEventListener("alert", ()=>{
878    console.log("alert listener callback");
879})
880```
881
882
883### removeEventListener<sup>9+</sup>
884
885removeEventListener(type: string, callback?: WorkerEventListener): void
886
887Removes an event listener for the Worker thread. This API provides the same functionality as [off<sup>9+</sup>](#off9).
888
889**Atomic service API**: This API can be used in atomic services since API version 12.
890
891**System capability**: SystemCapability.Utils.Lang
892
893**Parameters**
894
895| Name  | Type                                        | Mandatory| Description                        |
896| -------- | -------------------------------------------- | ---- | ---------------------------- |
897| type     | string                                       | Yes  | Type of the event for which the event listener is to be removed.    |
898| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when the listener is removed.|
899
900**Error codes**
901
902For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
903
904| ID| Error Message                     |
905| -------- | ------------------------------- |
906| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
907| 10200004 | The Worker instance is not running. |
908
909**Example**
910
911```ts
912const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
913workerInstance.addEventListener("alert", ()=>{
914    console.log("alert listener callback");
915})
916workerInstance.removeEventListener("alert");
917```
918
919
920### dispatchEvent<sup>9+</sup>
921
922dispatchEvent(event: Event): boolean
923
924Dispatches the event defined for the Worker thread.
925
926**Atomic service API**: This API can be used in atomic services since API version 12.
927
928**System capability**: SystemCapability.Utils.Lang
929
930**Parameters**
931
932| Name| Type           | Mandatory| Description            |
933| ------ | --------------- | ---- | ---------------- |
934| event  | [Event](#event) | Yes  | Event to dispatch.|
935
936**Return value**
937
938| Type   | Description                           |
939| ------- | ------------------------------- |
940| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|
941
942**Error codes**
943
944For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
945
946| ID| Error Message                     |
947| -------- | ------------------------------- |
948| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
949| 10200004 | The Worker instance is not running. |
950
951**Example**
952
953```ts
954const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
955
956workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet.
957```
958
959The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows:
960
961```ts
962import { worker, MessageEvents } from '@kit.ArkTS';
963
964const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
965
966// Usage 1:
967workerInstance.on("alert_on", ()=>{
968    console.log("alert listener callback");
969})
970workerInstance.once("alert_once", ()=>{
971    console.log("alert listener callback");
972})
973workerInstance.addEventListener("alert_add", ()=>{
974    console.log("alert listener callback");
975})
976
977// The event listener created by once is removed after being executed once.
978workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); // timeStamp is not supported yet.
979// The event listener created by on will not be proactively deleted.
980workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
981workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
982// The event listener created by addEventListener will not be proactively deleted.
983workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
984workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
985
986// Usage 2:
987// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
988// When type = "message", the event handler defined by onmessage will also be executed.
989// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
990// When type = "error", the event handler defined by onerror will also be executed.
991// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.
992
993workerInstance.addEventListener("message", ()=>{
994    console.log("message listener callback");
995})
996workerInstance.onmessage = (e: MessageEvents): void => {
997    console.log("onmessage : message listener callback");
998}
999// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
1000workerInstance.dispatchEvent({type:"message", timeStamp:0});
1001```
1002
1003
1004### removeAllListener<sup>9+</sup>
1005
1006removeAllListener(): void
1007
1008Removes all event listeners for the Worker thread.
1009
1010**Atomic service API**: This API can be used in atomic services since API version 12.
1011
1012**System capability**: SystemCapability.Utils.Lang
1013
1014**Error codes**
1015
1016For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
1017
1018| ID| Error Message                     |
1019| -------- | ------------------------------- |
1020| 10200004 | The Worker instance is not running. |
1021
1022**Example**
1023
1024```ts
1025const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
1026workerInstance.addEventListener("alert", ()=>{
1027    console.log("alert listener callback");
1028})
1029workerInstance.removeAllListener();
1030```
1031
1032
1033## ThreadWorkerGlobalScope<sup>9+</sup>
1034
1035Implements communication between the Worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the Worker thread. The **ThreadWorkerGlobalScope** class inherits from [GlobalScope<sup>9+</sup>](#globalscope9).
1036
1037### postMessage<sup>9+</sup>
1038
1039postMessage(messageObject: Object, transfer: ArrayBuffer[]): void;
1040
1041Sends a message from the Worker thread to the host thread by transferring object ownership.
1042
1043**Atomic service API**: This API can be used in atomic services since API version 11.
1044
1045**System capability**: SystemCapability.Utils.Lang
1046
1047**Parameters**
1048
1049| Name  | Type         | Mandatory| Description                                                        |
1050| -------- | ------------- | ---- | ------------------------------------------------------------ |
1051| messageObject  | Object        | Yes  | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
1052| transfer | ArrayBuffer[] | Yes  | ArrayBuffer instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null.|
1053
1054**Error codes**
1055
1056For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1057
1058| ID| Error Message                               |
1059| -------- | ----------------------------------------- |
1060| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1061| 10200004 | The Worker instance is not running.           |
1062| 10200006 | An exception occurred during serialization. |
1063
1064**Example**
1065
1066```ts
1067// Main thread
1068import { worker, MessageEvents } from '@kit.ArkTS';
1069
1070const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
1071workerInstance.postMessage("hello world");
1072workerInstance.onmessage = (e: MessageEvents): void => {
1073    console.log("receive data from worker.ets");
1074}
1075```
1076
1077```ts
1078// worker.ets
1079import { worker, MessageEvents } from '@kit.ArkTS';
1080
1081const workerPort = worker.workerPort;
1082workerPort.onmessage = (e: MessageEvents): void => {
1083    let buffer = new ArrayBuffer(8);
1084    workerPort.postMessage(buffer, [buffer]);
1085}
1086```
1087
1088### postMessage<sup>9+</sup>
1089
1090postMessage(messageObject: Object, options?: PostMessageOptions): void
1091
1092Sends a message from the Worker thread to the host thread by transferring object ownership or copying data.
1093
1094**Atomic service API**: This API can be used in atomic services since API version 11.
1095
1096**System capability**: SystemCapability.Utils.Lang
1097
1098**Parameters**
1099
1100| Name | Type                                     | Mandatory| Description                                                        |
1101| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1102| messageObject | Object                                    | Yes  | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
1103| options | [PostMessageOptions](#postmessageoptions) | No  | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the host thread and becomes unavailable in the Worker thread. The objects are available only in the host thread.<br>If this parameter is not specified, the default value **undefined** is used, and information is transferred to the host thread by copying data.|
1104
1105**Error codes**
1106
1107For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1108
1109| ID| Error Message                               |
1110| -------- | ----------------------------------------- |
1111| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1112| 10200004 | The Worker instance is not running.           |
1113| 10200006 | An exception occurred during serialization. |
1114
1115**Example**
1116
1117```ts
1118// Main thread
1119import { worker, MessageEvents } from '@kit.ArkTS';
1120
1121const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
1122workerInstance.postMessage("hello world");
1123workerInstance.onmessage = (e: MessageEvents): void => {
1124    console.log("receive data from worker.ets");
1125}
1126```
1127
1128```ts
1129// worker.ets
1130import { worker, MessageEvents } from '@kit.ArkTS';
1131
1132const workerPort = worker.workerPort;
1133workerPort.onmessage = (e: MessageEvents): void => {
1134    workerPort.postMessage("receive data from main thread");
1135}
1136```
1137
1138
1139### postMessageWithSharedSendable<sup>12+</sup>
1140
1141postMessageWithSharedSendable(message: Object, transfer?: ArrayBuffer[]): void
1142
1143Sends a message from the Worker thread to the host thread. In the message, a sendable object is passed by reference, and a non-sendable object is passed by serialization.
1144
1145**Atomic service API**: This API can be used in atomic services since API version 12.
1146
1147**System capability**: SystemCapability.Utils.Lang
1148
1149**Parameters**
1150
1151| Name | Type                                     | Mandatory| Description                                                        |
1152| --------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1153| message   | Object	     | Yes  | Data to be sent to the host thread. The data object must be sequenceable or sendable. For details about the supported sequenceable types, see [Sequenceable Data Types](#sequenceable-data-types). For details about the supported sendable types, see [Sendable Data Types](../../arkts-utils/arkts-sendable.md#sendable-data-types).|
1154| transfer  | ArrayBuffer[] | No  | ArrayBuffer instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null. The default value is an empty array.|
1155
1156**Error codes**
1157
1158For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1159
1160| ID| Error Message                               |
1161| -------- | ----------------------------------------- |
1162| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1163| 10200004 | The Worker instance is not running.           |
1164| 10200006 | An exception occurred during serialization. |
1165
1166**Example**
1167
1168<!--code_no_check-->
1169```ts
1170// The worker file path is entry/src/main/ets/workers/Worker.ets.
1171// Worker.ets
1172// Create a SendableObject instance and pass it to the host thread through the Worker thread.
1173
1174import { SendableObject } from '../pages/sendable'
1175import { worker, ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@kit.ArkTS';
1176
1177const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
1178workerPort.onmessage = (e: MessageEvents) => {
1179  let object: SendableObject = new SendableObject();
1180  workerPort.postMessageWithSharedSendable(object);
1181}
1182```
1183
1184```ts
1185// sendable.ets
1186// Define SendableObject.
1187
1188@Sendable
1189export class SendableObject {
1190  a:number = 45;
1191}
1192```
1193
1194<!--code_no_check-->
1195```ts
1196// Index.ets
1197// Receive the data passed from the Worker thread to the host thread and access its properties.
1198
1199import { worker, MessageEvents } from '@kit.ArkTS';
1200import { SendableObject } from './sendable'
1201
1202const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
1203workerInstance.postMessage(1);
1204workerInstance.onmessage = (e: MessageEvents) => {
1205  let obj: SendableObject = e.data;
1206  console.info("sendable index obj is: " + obj.a);
1207}
1208```
1209
1210
1211### callGlobalCallObjectMethod<sup>11+</sup>
1212
1213callGlobalCallObjectMethod(instanceName: string, methodName: string, timeout: number, ...args: Object[]): Object
1214
1215Calls a method of an object registered with the host thread. This API is called by the Worker thread. The invoking is synchronous for the Worker thread and asynchronous for the host thread. The return value is transferred through serialization.
1216
1217**Atomic service API**: This API can be used in atomic services since API version 12.
1218
1219**System capability**: SystemCapability.Utils.Lang
1220
1221**Parameters**
1222
1223| Name | Type                                     | Mandatory| Description                                                        |
1224| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1225| instanceName | string                                    | Yes  | Key used for registration. It is used to search for the object in the host thread.|
1226| methodName | string | Yes| Name of the method to call. Note that the method cannot be modified by async or generator, or return results asynchronously by using the asynchronous mechanism at the bottom layer. Otherwise, an exception is thrown.|
1227| timeout | number | Yes| Maximum duration that the current synchronous invoking waits, in ms. The value is an integer ranging from 1 to 5000. The value **0** means that the 5000 ms duration is used.|
1228| args | Object[] | No| Array of parameters in the method.|
1229
1230**Return value**
1231
1232| Type                                 | Description                           |
1233| ------------------------------------- | ------------------------------- |
1234| Object | Return value of the method in the host thread. The return value must be serializable. For details, see [Sequenceable Data Types](#sequenceable-data-types).|
1235
1236**Error codes**
1237
1238For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1239
1240| ID| Error Message                               |
1241| -------- | ----------------------------------------- |
1242| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1243| 10200004 | Worker instance is not running.           |
1244| 10200006 | An exception occurred during serialization. |
1245| 10200019 | The globalCallObject is not registered. |
1246| 10200020 | The method to be called is not callable or is an async method or a generator. |
1247| 10200021 | The global call exceeds the timeout. |
1248
1249**Example**
1250```ts
1251// worker.ets
1252import { worker, MessageEvents } from '@kit.ArkTS';
1253
1254const workerPort = worker.workerPort;
1255workerPort.onmessage = (e: MessageEvents): void => {
1256  try {
1257    // The method to call does not carry an input parameter.
1258    let res : string = workerPort.callGlobalCallObjectMethod("myObj", "getMessage", 0) as string;
1259    console.info("worker:", res) // worker: this is a message from TestObj
1260  } catch (error) {
1261    // Exception handling.
1262    console.error("worker: error code is " + error.code + " error message is " + error.message);
1263  }
1264  try {
1265    // The method to call carries input parameters.
1266    let res : string = workerPort.callGlobalCallObjectMethod("myObj", "getMessageWithInput", 0, "hello there!") as string;
1267    console.info("worker:", res) //worker: this is a message from TestObj with input: hello there!
1268  } catch (error) {
1269    // Exception handling.
1270    console.error("worker: error code is " + error.code + " error message is " + error.message);
1271  }
1272}
1273```
1274
1275### close<sup>9+</sup>
1276
1277close(): void
1278
1279Terminates the Worker thread to stop it from receiving messages.
1280
1281**Atomic service API**: This API can be used in atomic services since API version 11.
1282
1283**System capability**: SystemCapability.Utils.Lang
1284
1285**Error codes**
1286
1287For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
1288
1289| ID| Error Message                     |
1290| -------- | ------------------------------- |
1291| 10200004 | The Worker instance is not running. |
1292
1293**Example**
1294
1295```ts
1296// Main thread
1297import { worker } from '@kit.ArkTS';
1298
1299const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
1300```
1301
1302```ts
1303// worker.ets
1304import { worker, MessageEvents } from '@kit.ArkTS';
1305
1306const workerPort = worker.workerPort;
1307workerPort.onmessage = (e: MessageEvents): void => {
1308    workerPort.close()
1309}
1310```
1311
1312
1313### onmessage<sup>9+</sup>
1314
1315onmessage?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) =&gt; void
1316
1317Called when the Worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the Worker thread. In the callback function, **this** indicates the caller's [ThreadWorkerGlobalScope](#threadworkerglobalscope9), and the **ev** type is [MessageEvents](#messageevents9), indicating the received message data.
1318
1319**Atomic service API**: This API can be used in atomic services since API version 11.
1320
1321**System capability**: SystemCapability.Utils.Lang
1322
1323**Error codes**
1324
1325For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1326
1327| ID| Error Message                                  |
1328| -------- | -------------------------------------------- |
1329| 401      | Parameter error. Possible causes: 1. Incorrect parameter types. |
1330| 10200004 | The Worker instance is not running.              |
1331| 10200005 | The called API is not supported in the worker thread. |
1332
1333**Example**
1334
1335```ts
1336// Main thread
1337import { worker } from '@kit.ArkTS';
1338
1339const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
1340workerInstance.postMessage("hello world");
1341```
1342
1343```ts
1344// worker.ets
1345import { worker, MessageEvents } from '@kit.ArkTS';
1346
1347const workerPort = worker.workerPort;
1348workerPort.onmessage = (e: MessageEvents): void => {
1349    console.log("receive main thread message");
1350}
1351```
1352
1353
1354### onmessageerror<sup>9+</sup>
1355
1356onmessageerror?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) =&gt; void
1357
1358Called when the Worker thread receives a message that cannot be deserialized. The event handler is executed in the Worker thread. In the callback function, **this** indicates the caller's [ThreadWorkerGlobalScope](#threadworkerglobalscope9), and the **ev** type is [MessageEvents](#messageevents9), indicating the received message data.
1359
1360**Atomic service API**: This API can be used in atomic services since API version 11.
1361
1362**System capability**: SystemCapability.Utils.Lang
1363
1364**Error codes**
1365
1366For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1367
1368| ID| Error Message                                  |
1369| -------- | -------------------------------------------- |
1370| 401      | Parameter error. Possible causes: 1. Incorrect parameter types. |
1371| 10200004 | The Worker instance is not running.              |
1372| 10200005 | The called API is not supported in the worker thread. |
1373
1374**Example**
1375
1376```ts
1377// Main thread
1378import { worker } from '@kit.ArkTS';
1379
1380const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
1381```
1382
1383```ts
1384// worker.ets
1385import { worker, MessageEvents } from '@kit.ArkTS';
1386
1387const workerPort = worker.workerPort;
1388workerPort.onmessageerror = (err: MessageEvents) => {
1389    console.log("worker.ets onmessageerror");
1390}
1391```
1392
1393
1394## WorkerEventListener<sup>9+</sup>
1395
1396Implements event listening.
1397
1398### (event: Event)<sup>9+</sup>
1399
1400(event: Event): void | Promise&lt;void&gt;
1401
1402**Atomic service API**: This API can be used in atomic services since API version 12.
1403
1404**System capability**: SystemCapability.Utils.Lang
1405
1406**Parameters**
1407
1408| Name| Type           | Mandatory| Description          |
1409| ------ | --------------- | ---- | -------------- |
1410| event  | [Event](#event) | Yes  | Event class for the callback to invoke.|
1411
1412**Return value**
1413
1414| Type                                 | Description                           |
1415| ------------------------------------- | ------------------------------- |
1416| void&nbsp;\|&nbsp;Promise&lt;void&gt; | Returns no value or returns a **Promise**.|
1417
1418**Error codes**
1419
1420For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1421
1422| ID| Error Message                                  |
1423| -------- | -------------------------------------------- |
1424| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1425| 10200004 | Worker instance is not running.          |
1426| 10200005 | The invoked API is not supported in workers. |
1427
1428**Example**
1429
1430```ts
1431const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets");
1432workerInstance.addEventListener("alert", ()=>{
1433    console.log("alert listener callback");
1434})
1435```
1436
1437
1438## GlobalScope<sup>9+</sup>
1439
1440Implements the running environment of the Worker thread. The **GlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9).
1441
1442### Attributes
1443
1444**Atomic service API**: This API can be used in atomic services since API version 11.
1445
1446**System capability**: SystemCapability.Utils.Lang
1447
1448| Name| Type                                                        | Readable| Writable| Description                                 |
1449| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
1450| name | string                                                       | Yes  | No  | Worker instance specified when there is a new Worker instance.|
1451| self | [GlobalScope](#globalscope9)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes  | No  | GlobalScope itself.                    |
1452
1453
1454### onerror<sup>9+</sup>
1455
1456onerror?: (ev: ErrorEvent) =&gt; void
1457
1458Called when an exception occurs during worker execution. The event handler is executed in the Worker thread. In the callback function, the **ev** type is [ErrorEvent](#errorevent), indicating the received abnormal data.
1459
1460**Atomic service API**: This API can be used in atomic services since API version 11.
1461
1462**System capability**: SystemCapability.Utils.Lang
1463
1464**Example**
1465
1466```ts
1467// Main thread
1468import { worker } from '@kit.ArkTS';
1469
1470const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets")
1471```
1472
1473```ts
1474// worker.ets
1475import { worker, ErrorEvent } from '@kit.ArkTS';
1476
1477const workerPort = worker.workerPort
1478workerPort.onerror = (err: ErrorEvent) => {
1479    console.log("worker.ets onerror" + err.message)
1480}
1481```
1482
1483## MessageEvents<sup>9+</sup>
1484
1485Holds the data transferred between Worker threads.
1486
1487**Atomic service API**: This API can be used in atomic services since API version 11.
1488
1489**System capability**: SystemCapability.Utils.Lang
1490
1491| Name| Type| Readable| Writable| Description              |
1492| ---- | ---- | ---- | ---- | ------------------ |
1493| data | any  | Yes  | No  | Data transferred between threads.|
1494
1495## MessageType<sup>7+</sup>
1496
1497type MessageType = 'message' | 'messageerror';
1498
1499Defines the message type.
1500
1501**Atomic service API**: This API can be used in atomic services since API version 12.
1502
1503**System capability**: SystemCapability.Utils.Lang
1504
1505| Type | Description              |
1506| ---- | ------------------ |
1507| 'message'  | The message type is message, fixed at **'message'**.|
1508| 'messageerror'  | The message type is messageerror, fixed at **'messageerror'**.|
1509
1510## Worker<sup>(deprecated)</sup>
1511
1512Before using the following APIs, you must create a Worker instance. The **Worker** class inherits from [EventTarget](#eventtargetdeprecated).
1513
1514> **NOTE**
1515>
1516> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker<sup>9+</sup>](#threadworker9) instead.
1517
1518### constructor<sup>(deprecated)</sup>
1519
1520constructor(scriptURL: string, options?: WorkerOptions)
1521
1522A constructor used to create a Worker instance.
1523
1524> **NOTE**<br>
1525> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.constructor<sup>9+</sup>](#constructor9) instead.
1526
1527**System capability**: SystemCapability.Utils.Lang
1528
1529**Parameters**
1530
1531| Name   | Type                           | Mandatory| Description                                                        |
1532| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
1533| scriptURL | string                          | Yes  | URL of the Worker thread file. For details about the rules, see [Precautions for File URLs](../../arkts-utils/worker-introduction.md#precautions-for-file-urls).|
1534| options   | [WorkerOptions](#workeroptions) | No  | Options that can be set for the Worker instance.                                          |
1535
1536**Example**
1537
1538The following code snippet shows how to load the Worker thread file of the ability in the stage model. For details about how to use the library to load the Worker thread file, see [Precautions for File URLs](../../arkts-utils/worker-introduction.md#precautions-for-file-urls).
1539
1540
1541```ts
1542import { worker } from '@kit.ArkTS';
1543
1544// Two scenarios are involved.
1545
1546// Scenario 1: URL of the Worker thread file: "entry/src/main/ets/workers/worker.ets"
1547const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ets', {name:"first worker in Stage model"});
1548
1549// Scenario 2: URL of the Worker thread file: "phone/src/main/ets/ThreadFile/workers/worker.ets"
1550const workerStageModel02 = new worker.ThreadWorker('phone/ets/ThreadFile/workers/worker.ets');
1551```
1552
1553### postMessage<sup>(deprecated)</sup>
1554
1555postMessage(message: Object, transfer: ArrayBuffer[]): void
1556
1557Sends a message from the host thread to the Worker thread by transferring object ownership.
1558
1559> **NOTE**<br>
1560> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage<sup>9+</sup>](#postmessage9) instead.
1561
1562**System capability**: SystemCapability.Utils.Lang
1563
1564**Parameters**
1565
1566| Name  | Type         | Mandatory| Description                                                        |
1567| -------- | ------------- | ---- | ------------------------------------------------------------ |
1568| message  | Object        | Yes  | Data to be sent to the Worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
1569| transfer | ArrayBuffer[] | Yes  | ArrayBuffer instance holding an array of objects for which the ownership is transferred to the Worker thread. After the transfer, the objects are available only in the Worker thread. The array cannot be null.|
1570
1571**Example**
1572
1573```ts
1574const workerInstance = new worker.Worker("workers/worker.ets");
1575
1576let buffer = new ArrayBuffer(8);
1577workerInstance.postMessage(buffer, [buffer]);
1578```
1579
1580### postMessage<sup>(deprecated)</sup>
1581
1582postMessage(message: Object, options?: PostMessageOptions): void
1583
1584Sends a message from the host thread to the Worker thread by transferring object ownership or copying data.
1585
1586> **NOTE**<br>
1587> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage<sup>9+</sup>](#postmessage9-1) instead.
1588
1589**System capability**: SystemCapability.Utils.Lang
1590
1591**Parameters**
1592
1593| Name | Type                                     | Mandatory| Description                                                        |
1594| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1595| message | Object                                    | Yes  | Data to be sent to the Worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
1596| options | [PostMessageOptions](#postmessageoptions) | No  | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the Worker thread and becomes unavailable in the host thread. The objects are available only in the Worker thread.<br>If this parameter is not specified, the default value **undefined** is used, and information is transferred to the Worker thread by copying data.|
1597
1598**Example**
1599
1600```ts
1601const workerInstance = new worker.Worker("workers/worker.ets");
1602
1603workerInstance.postMessage("hello world");
1604
1605let buffer = new ArrayBuffer(8);
1606workerInstance.postMessage(buffer, [buffer]);
1607```
1608
1609
1610### on<sup>(deprecated)</sup>
1611
1612on(type: string, listener: EventListener): void
1613
1614Adds an event listener for the Worker thread. This API provides the same functionality as [addEventListener<sup>(deprecated)</sup>](#addeventlistenerdeprecated).
1615
1616> **NOTE**<br>
1617> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.on<sup>9+</sup>](#on9) instead.
1618
1619**System capability**: SystemCapability.Utils.Lang
1620
1621**Parameters**
1622
1623| Name  | Type                                     | Mandatory| Description            |
1624| -------- | ----------------------------------------- | ---- | ---------------- |
1625| type     | string                                    | Yes  | Type of the event to listen for.|
1626| listener | [EventListener](#eventlistenerdeprecated) | Yes  | Callback to invoke when an event of the specified type occurs.      |
1627
1628**Example**
1629
1630```ts
1631const workerInstance = new worker.Worker("workers/worker.ets");
1632workerInstance.on("alert", ()=>{
1633    console.log("alert listener callback");
1634})
1635```
1636
1637
1638### once<sup>(deprecated)</sup>
1639
1640once(type: string, listener: EventListener): void
1641
1642Adds an event listener for the Worker thread and removes the event listener after it is invoked once.
1643
1644> **NOTE**<br>
1645> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.once<sup>9+</sup>](#once9) instead.
1646
1647**System capability**: SystemCapability.Utils.Lang
1648
1649**Parameters**
1650
1651| Name  | Type                                     | Mandatory| Description            |
1652| -------- | ----------------------------------------- | ---- | ---------------- |
1653| type     | string                                    | Yes  | Type of the event to listen for.|
1654| listener | [EventListener](#eventlistenerdeprecated) | Yes  | Callback to invoke when an event of the specified type occurs.      |
1655
1656**Example**
1657
1658```ts
1659const workerInstance = new worker.Worker("workers/worker.ets");
1660workerInstance.once("alert", ()=>{
1661    console.log("alert listener callback");
1662})
1663```
1664
1665
1666### off<sup>(deprecated)</sup>
1667
1668off(type: string, listener?: EventListener): void
1669
1670Removes an event listener for the Worker thread. This API provides the same functionality as [removeEventListener<sup>(deprecated)</sup>](#removeeventlistenerdeprecated).
1671
1672> **NOTE**<br>
1673> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.off<sup>9+</sup>](#off9) instead.
1674
1675**System capability**: SystemCapability.Utils.Lang
1676
1677**Parameters**
1678
1679| Name  | Type                                     | Mandatory| Description                |
1680| -------- | ----------------------------------------- | ---- | -------------------- |
1681| type     | string                                    | Yes  | Type of the event for which the event listener is to be removed.|
1682| listener | [EventListener](#eventlistenerdeprecated) | No  | Callback to invoke when the listener is removed.|
1683
1684**Example**
1685
1686```ts
1687const workerInstance = new worker.Worker("workers/worker.ets");
1688// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener.
1689workerInstance.off("alert");
1690```
1691
1692
1693### terminate<sup>(deprecated)</sup>
1694
1695terminate(): void
1696
1697Terminates the Worker thread to stop it from receiving messages.
1698
1699> **NOTE**<br>
1700> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.terminate<sup>9+</sup>](#terminate9) instead.
1701
1702**System capability**: SystemCapability.Utils.Lang
1703
1704**Example**
1705
1706```ts
1707const workerInstance = new worker.Worker("workers/worker.ets");
1708workerInstance.terminate();
1709```
1710
1711
1712### onexit<sup>(deprecated)</sup>
1713
1714onexit?: (code: number) =&gt; void
1715
1716Called when the Worker thread exits. The event handler is executed in the host thread. In the callback function, the **code** value is of the number type, where the value **1** indicates abnormal exit and **0** indicates normal exit.
1717
1718> **NOTE**<br>
1719> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onexit<sup>9+</sup>](#onexit9) instead.
1720
1721**System capability**: SystemCapability.Utils.Lang
1722
1723**Example**
1724
1725```ts
1726const workerInstance = new worker.Worker("workers/worker.ets");
1727workerInstance.onexit = (code) => {
1728    console.log("onexit");
1729}
1730
1731// onexit is executed in either of the following ways:
1732// Main thread
1733workerInstance.terminate();
1734
1735// Worker thread
1736//parentPort.close()
1737```
1738
1739
1740### onerror<sup>(deprecated)</sup>
1741
1742onerror?: (err: ErrorEvent) =&gt; void
1743
1744Called when an exception occurs during worker execution. The event handler is executed in the host thread. In the callback function, the **err** type is [ErrorEvent](#errorevent), indicating the received abnormal data.
1745
1746> **NOTE**<br>
1747> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onerror<sup>9+</sup>](#onerror9) instead.
1748
1749**System capability**: SystemCapability.Utils.Lang
1750
1751**Example**
1752
1753```ts
1754import { worker, ErrorEvent } from '@kit.ArkTS';
1755
1756const workerInstance = new worker.Worker("workers/worker.ets");
1757workerInstance.onerror = (err: ErrorEvent) => {
1758  console.log("onerror" + err.message);
1759}
1760```
1761
1762
1763### onmessage<sup>(deprecated)</sup>
1764
1765onmessage?: (event: MessageEvent) =&gt; void
1766
1767Called when the host thread receives a message sent by the Worker thread through **workerPort.postMessage**. The event handler is executed in the host thread. In the callback function, the **event** type is [MessageEvent](#messageeventt), indicating the received message data.
1768
1769> **NOTE**<br>
1770> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessage<sup>9+</sup>](#onmessage9) instead.
1771
1772**System capability**: SystemCapability.Utils.Lang
1773
1774**Example**
1775
1776```ts
1777import { worker } from '@kit.ArkTS';
1778
1779const workerInstance = new worker.Worker("workers/worker.ets");
1780workerInstance.onmessage = (): void => {
1781    console.log("onmessage");
1782}
1783```
1784
1785
1786### onmessageerror<sup>(deprecated)</sup>
1787
1788onmessageerror?: (event: MessageEvent) =&gt; void
1789
1790Called when the Worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. In the callback function, the **event** type is [MessageEvent](#messageeventt), indicating the received message data.
1791
1792> **NOTE**<br>
1793> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror<sup>9+</sup>](#onmessageerror9) instead.
1794
1795**System capability**: SystemCapability.Utils.Lang
1796
1797**Example**
1798
1799```ts
1800import { worker } from '@kit.ArkTS';
1801
1802const workerInstance = new worker.Worker("workers/worker.ets");
1803workerInstance.onmessageerror = (err) => {
1804    console.log("onmessageerror");
1805}
1806```
1807
1808
1809## EventTarget<sup>(deprecated)</sup>
1810> **NOTE**<br>
1811> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventTarget<sup>9+</sup>](#workereventtarget9) instead.
1812
1813### addEventListener<sup>(deprecated)</sup>
1814
1815addEventListener(type: string, listener: EventListener): void
1816
1817Adds an event listener for the Worker thread. This API provides the same functionality as [on<sup>(deprecated)</sup>](#ondeprecated).
1818
1819> **NOTE**<br>
1820> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addEventListener<sup>9+</sup>](#addeventlistener9) instead.
1821
1822**System capability**: SystemCapability.Utils.Lang
1823
1824**Parameters**
1825
1826| Name  | Type                                     | Mandatory| Description            |
1827| -------- | ----------------------------------------- | ---- | ---------------- |
1828| type     | string                                    | Yes  | Type of the event to listen for.|
1829| listener | [EventListener](#eventlistenerdeprecated) | Yes  | Callback to invoke when an event of the specified type occurs.    |
1830
1831**Example**
1832
1833```ts
1834const workerInstance = new worker.Worker("workers/worker.ets");
1835workerInstance.addEventListener("alert", ()=>{
1836    console.log("alert listener callback");
1837})
1838```
1839
1840
1841### removeEventListener<sup>(deprecated)</sup>
1842
1843removeEventListener(type: string, callback?: EventListener): void
1844
1845Removes an event listener for the Worker thread. This API provides the same functionality as [off<sup>(deprecated)</sup>](#offdeprecated).
1846
1847> **NOTE**<br>
1848> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeEventListener<sup>9+</sup>](#removeeventlistener9) instead.
1849
1850**System capability**: SystemCapability.Utils.Lang
1851
1852**Parameters**
1853
1854| Name  | Type                                     | Mandatory| Description                    |
1855| -------- | ----------------------------------------- | ---- | ------------------------ |
1856| type     | string                                    | Yes  | Type of the event for which the event listener is to be removed.|
1857| callback | [EventListener](#eventlistenerdeprecated) | No  | Callback to invoke when the listener is removed.|
1858
1859**Example**
1860
1861```ts
1862const workerInstance = new worker.Worker("workers/worker.ets");
1863workerInstance.addEventListener("alert", ()=>{
1864    console.log("alert listener callback");
1865})
1866workerInstance.removeEventListener("alert");
1867```
1868
1869
1870### dispatchEvent<sup>(deprecated)</sup>
1871
1872dispatchEvent(event: Event): boolean
1873
1874Dispatches the event defined for the Worker thread.
1875
1876> **NOTE**<br>
1877> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [dispatchEvent<sup>9+</sup>](#dispatchevent9) instead.
1878
1879**System capability**: SystemCapability.Utils.Lang
1880
1881**Parameters**
1882
1883| Name| Type           | Mandatory| Description            |
1884| ------ | --------------- | ---- | ---------------- |
1885| event  | [Event](#event) | Yes  | Event to dispatch.|
1886
1887**Return value**
1888
1889| Type   | Description                           |
1890| ------- | ------------------------------- |
1891| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|
1892
1893**Example**
1894
1895```ts
1896const workerInstance = new worker.Worker("workers/worker.ets");
1897
1898workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet.
1899```
1900
1901The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows:
1902
1903```ts
1904const workerInstance = new worker.Worker("workers/worker.ets");
1905
1906// Usage 1:
1907workerInstance.on("alert_on", ()=>{
1908    console.log("alert listener callback");
1909})
1910workerInstance.once("alert_once", ()=>{
1911    console.log("alert listener callback");
1912})
1913workerInstance.addEventListener("alert_add", ()=>{
1914    console.log("alert listener callback");
1915})
1916
1917// The event listener created by once is removed after being executed once.
1918workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); // timeStamp is not supported yet.
1919// The event listener created by on will not be proactively deleted.
1920workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
1921workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
1922// The event listener created by addEventListener will not be proactively deleted.
1923workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
1924workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
1925
1926// Usage 2:
1927// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
1928// When type = "message", the event handler defined by onmessage will also be executed.
1929// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
1930// When type = "error", the event handler defined by onerror will also be executed.
1931// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.
1932
1933workerInstance.addEventListener("message", ()=>{
1934    console.log("message listener callback");
1935})
1936workerInstance.onmessage = function() {
1937    console.log("onmessage : message listener callback");
1938}
1939// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
1940workerInstance.dispatchEvent({type:"message", timeStamp:0});
1941```
1942### removeAllListener<sup>(deprecated)</sup>
1943
1944removeAllListener(): void
1945
1946Removes all event listeners for the Worker thread.
1947
1948> **NOTE**<br>
1949> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeAllListener<sup>9+</sup>](#removealllistener9) instead.
1950
1951**System capability**: SystemCapability.Utils.Lang
1952
1953**Example**
1954
1955```ts
1956const workerInstance = new worker.Worker("workers/worker.ets");
1957workerInstance.addEventListener("alert", ()=>{
1958    console.log("alert listener callback");
1959})
1960workerInstance.removeAllListener();
1961```
1962
1963
1964## DedicatedWorkerGlobalScope<sup>(deprecated)</sup>
1965
1966Implements communication between the Worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the Worker thread. This class inherits from [WorkerGlobalScope](#workerglobalscopedeprecated).
1967
1968> **NOTE**<br>
1969> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>](#threadworkerglobalscope9) instead.
1970
1971### postMessage<sup>(deprecated)</sup>
1972
1973postMessage(messageObject: Object, transfer: Transferable[]): void
1974
1975Sends a message from the Worker thread to the host thread by transferring object ownership.
1976
1977> **NOTE**<br>
1978> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.postMessage<sup>9+</sup>](#postmessage9-2).
1979
1980**System capability**: SystemCapability.Utils.Lang
1981
1982**Parameters**
1983
1984| Name | Type                                     | Mandatory| Description                                                        |
1985| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
1986| messageObject | Object                                    | Yes  | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
1987| transfer| Transferable[]                            | Yes  | Currently, this parameter is not supported.                                        |
1988
1989### postMessage<sup>9+</sup>
1990
1991postMessage(messageObject: Object, transfer: ArrayBuffer[]): void
1992
1993Sends a message from the Worker thread to the host thread by transferring object ownership.
1994
1995> **NOTE**
1996>
1997> The **DedicatedWorkerGlobalScope** class is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.postMessage<sup>9+</sup>](#postmessage9-2).
1998
1999**System capability**: SystemCapability.Utils.Lang
2000
2001**Parameters**
2002
2003| Name  | Type         | Mandatory| Description                                                        |
2004| -------- | ------------- | ---- | ------------------------------------------------------------ |
2005| messageObject  | Object        | Yes  | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
2006| transfer | ArrayBuffer[] | Yes  | ArrayBuffer instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null.|
2007
2008**Example**
2009
2010```ts
2011// Main thread
2012import { worker } from '@kit.ArkTS';
2013
2014const workerInstance = new worker.Worker("workers/worker.ets");
2015workerInstance.postMessage("hello world");
2016workerInstance.onmessage = (): void => {
2017    // let data = e.data;
2018    console.log("receive data from worker.ets");
2019}
2020```
2021```ts
2022// worker.ets
2023import { worker } from '@kit.ArkTS';
2024
2025const workerPort = worker.workerPort;
2026workerPort.onmessage = (): void => {
2027    // let data = e.data;
2028    let buffer = new ArrayBuffer(5)
2029    workerPort.postMessage(buffer, [buffer]);
2030}
2031```
2032
2033### postMessage<sup>(deprecated)</sup>
2034
2035postMessage(messageObject: Object, options?: PostMessageOptions): void
2036
2037Sends a message from the Worker thread to the host thread by transferring object ownership or copying data.
2038
2039> **NOTE**<br>
2040> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.postMessage<sup>9+</sup>](#postmessage9-3).
2041
2042**System capability**: SystemCapability.Utils.Lang
2043
2044**Parameters**
2045
2046| Name | Type                                     | Mandatory| Description                                                        |
2047| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
2048| messageObject | Object                                    | Yes  | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
2049| options | [PostMessageOptions](#postmessageoptions) | No  | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the host thread and becomes unavailable in the Worker thread. The objects are available only in the host thread.<br>If this parameter is not specified, the default value **undefined** is used, and information is transferred to the host thread by copying data.|
2050
2051**Example**
2052
2053<!--no_check-->
2054```ts
2055// Main thread
2056import { worker } from '@kit.ArkTS';
2057
2058const workerInstance = new worker.Worker("entry/ets/workers/worker.ets");
2059workerInstance.postMessage("hello world");
2060workerInstance.onmessage = (): void => {
2061    console.log("receive data from worker.ets");
2062}
2063```
2064```ts
2065// worker.ets
2066import { ErrorEvent, MessageEvents, worker } from '@kit.ArkTS';
2067
2068const parentPort = worker.parentPort;
2069parentPort.onmessage = (e: MessageEvents) => {
2070  parentPort.postMessage("receive data from main thread");
2071}
2072```
2073
2074### close<sup>(deprecated)</sup>
2075
2076close(): void
2077
2078Terminates the Worker thread to stop it from receiving messages.
2079
2080> **NOTE**<br>
2081> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.close<sup>9+</sup>](#close9).
2082
2083**System capability**: SystemCapability.Utils.Lang
2084
2085**Example**
2086
2087```ts
2088// Main thread
2089import { worker } from '@kit.ArkTS';
2090
2091const workerInstance = new worker.Worker("workers/worker.ets");
2092```
2093```ts
2094// worker.ets
2095import { worker } from '@kit.ArkTS';
2096
2097const parentPort = worker.parentPort;
2098parentPort.onmessage = (): void => {
2099    parentPort.close()
2100}
2101```
2102
2103
2104### onmessage<sup>(deprecated)</sup>
2105
2106onmessage?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) =&gt; void
2107
2108Called when the Worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the Worker thread. In the callback function, **this** indicates the caller's [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated), and the **ev** type is [MessageEvent](#messageeventt), indicating the received message data.
2109
2110> **NOTE**<br>
2111> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.onmessage<sup>9+</sup>](#onmessage9-1).
2112
2113**System capability**: SystemCapability.Utils.Lang
2114
2115**Example**
2116
2117```ts
2118// Main thread
2119import { worker } from '@kit.ArkTS';
2120
2121const workerInstance = new worker.Worker("workers/worker.ets");
2122workerInstance.postMessage("hello world");
2123```
2124```ts
2125// worker.ets
2126import { worker } from '@kit.ArkTS';
2127
2128const parentPort = worker.parentPort;
2129parentPort.onmessage = (): void => {
2130    console.log("receive main thread message");
2131}
2132```
2133
2134
2135### onmessageerror<sup>(deprecated)</sup>
2136
2137onmessageerror?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) =&gt; void
2138
2139Called when the Worker thread receives a message that cannot be deserialized. The event handler is executed in the Worker thread. In the callback function, **this** indicates the caller's [DedicatedWorkerGlobalScope](#threadworkerglobalscope9), and the **ev** type is [MessageEvent](#dedicatedworkerglobalscopedeprecated), indicating the received message data.
2140
2141> **NOTE**<br>
2142> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.onmessageerror<sup>9+</sup>](#onmessageerror9-1).
2143
2144**System capability**: SystemCapability.Utils.Lang
2145
2146**Example**
2147
2148```ts
2149// Main thread
2150import { worker } from '@kit.ArkTS';
2151
2152const workerInstance = new worker.Worker("workers/worker.ets");
2153```
2154```ts
2155// worker.ets
2156import { worker } from '@kit.ArkTS';
2157
2158const parentPort = worker.parentPort;
2159parentPort.onmessageerror = () => {
2160    console.log("worker.ets onmessageerror")
2161}
2162```
2163
2164
2165## PostMessageOptions
2166
2167Defines the object for which the ownership is to be transferred during data transfer. The object must be an ArrayBuffer instance. After the ownership is transferred, the object becomes unavailable in the sender and can be used only in the receiver.
2168
2169**Atomic service API**: This API can be used in atomic services since API version 11.
2170
2171**System capability**: SystemCapability.Utils.Lang
2172
2173| Name    | Type    | Readable| Writable| Description                             |
2174| -------- | -------- | ---- | ---- | --------------------------------- |
2175| transfer | Object[] | Yes  | Yes  | **ArrayBuffer** array used to transfer the ownership. The array cannot be **null**.|
2176
2177
2178## Event
2179
2180Defines the event.
2181
2182**Atomic service API**: This API can be used in atomic services since API version 12.
2183
2184**System capability**: SystemCapability.Utils.Lang
2185
2186| Name     | Type  | Readable| Writable| Description                                        |
2187| --------- | ------ | ---- | ---- | -------------------------------------------- |
2188| type      | string | Yes  | No  | Type of the event.                            |
2189| timeStamp | number | Yes  | No  | Timestamp (accurate to millisecond) when the event is created. This parameter is not supported yet.|
2190
2191
2192## EventListener<sup>(deprecated)</sup>
2193
2194Implements event listening.
2195
2196> **NOTE**
2197>
2198> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventListener<sup>9+</sup>](#workereventlistener9) instead.
2199
2200### (evt: Event)<sup>(deprecated)</sup>
2201
2202(evt: Event): void | Promise&lt;void&gt;
2203
2204> **NOTE**
2205>
2206> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [(event:Event)<sup>9+</sup>](#event-event9) instead.
2207
2208**System capability**: SystemCapability.Utils.Lang
2209
2210**Parameters**
2211
2212| Name| Type           | Mandatory| Description          |
2213| ------ | --------------- | ---- | -------------- |
2214| evt    | [Event](#event) | Yes  | Event class for the callback to invoke.|
2215
2216**Return value**
2217
2218| Type                                 | Description                           |
2219| ------------------------------------- | ------------------------------- |
2220| void&nbsp;\|&nbsp;Promise&lt;void&gt; | Returns no value or returns a **Promise**.|
2221
2222**Example**
2223
2224```ts
2225const workerInstance = new worker.Worker("workers/worker.ets");
2226workerInstance.addEventListener("alert", ()=>{
2227    console.log("alert listener callback");
2228})
2229```
2230
2231
2232## ErrorEvent
2233
2234Provides detailed information about the exception that occurs during worker execution. The **ErrorEvent** class inherits from [Event](#event).
2235
2236**Atomic service API**: This API can be used in atomic services since API version 11.
2237
2238**System capability**: SystemCapability.Utils.Lang
2239
2240| Name    | Type  | Readable| Writable| Description                |
2241| -------- | ------ | ---- | ---- | -------------------- |
2242| message  | string | Yes  | No  | Information about the exception.|
2243| filename | string | Yes  | No  | File where the exception is located.|
2244| lineno   | number | Yes  | No  | Serial number of the line where the exception is located.    |
2245| colno    | number | Yes  | No  | Serial number of the column where the exception is located.    |
2246| error    | Object | Yes  | No  | Type of the exception.          |
2247
2248
2249## MessageEvent\<T\>
2250
2251Holds the data transferred between Worker threads.
2252
2253**Atomic service API**: This API can be used in atomic services since API version 12.
2254
2255**System capability**: SystemCapability.Utils.Lang
2256
2257| Name| Type| Readable| Writable| Description              |
2258| ---- | ---- | ---- | ---- | ------------------ |
2259| data | T    | Yes  | No  | Data transferred between threads.|
2260
2261
2262## WorkerGlobalScope<sup>(deprecated)</sup>
2263
2264Implements the running environment of the Worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtargetdeprecated).
2265
2266> **NOTE**<br>
2267> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope<sup>9+</sup>](#globalscope9) instead.
2268
2269### Attributes
2270
2271**System capability**: SystemCapability.Utils.Lang
2272
2273| Name| Type                                                        | Readable| Writable| Description                                 |
2274| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
2275| name | string                                                       | Yes  | No  | Worker instance specified when there is a new Worker instance.|
2276| self | [WorkerGlobalScope](#workerglobalscopedeprecated)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes  | No  | WorkerGlobalScope.              |
2277
2278
2279### onerror<sup>(deprecated)</sup>
2280
2281onerror?: (ev: ErrorEvent) =&gt; void
2282
2283Called when an exception occurs during worker execution. The event handler is executed in the Worker thread. In the callback function, the **ev** type is [ErrorEvent](#errorevent), indicating the received abnormal data.
2284
2285> **NOTE**<br>
2286> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope<sup>9+</sup>.onerror<sup>9+</sup>](#onerror9-1).
2287
2288**System capability**: SystemCapability.Utils.Lang
2289
2290**Example**
2291
2292```ts
2293// Main thread
2294import { worker } from '@kit.ArkTS';
2295
2296const workerInstance = new worker.Worker("workers/worker.ets")
2297```
2298```ts
2299// worker.ets
2300import { worker, ErrorEvent } from '@kit.ArkTS';
2301
2302const parentPort = worker.parentPort
2303parentPort.onerror = (err: ErrorEvent) => {
2304    console.log("worker.ets onerror" + err.message)
2305}
2306```
2307
2308
2309## More Information
2310
2311### Sequenceable Data Types
2312
2313The following object types are supported: basic types except Symbol, Date, String, RegExp, Array, Map, Set, Object (simple objects only, for example, objects created using **{}** or **new Object**), ArrayBuffer, and typedArray. (Note that only attributes can be transferred for common objects. Prototypes and methods cannot be transferred.)
2314
2315Exception: When an object created through a custom class is passed, no serialization error occurs. However, the attributes (such as Function) of the custom class cannot be passed through serialization.
2316> **NOTE**<br>
2317> An FA project of API version 9 is used as an example.
2318
2319```ts
2320// Main thread
2321import { worker, MessageEvents } from '@kit.ArkTS';
2322
2323const workerInstance = new worker.ThreadWorker("workers/worker.ets");
2324workerInstance.postMessage("message from main thread to worker");
2325workerInstance.onmessage = (d: MessageEvents): void => {
2326  // When the Worker thread passes obj2, data contains obj2, excluding the Init or SetName method.
2327  let data: string  = d.data;
2328}
2329```
2330```ts
2331// worker.ets
2332import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
2333
2334const workerPort = worker.workerPort;
2335class MyModel {
2336    name = "undefined"
2337    Init() {
2338        this.name = "MyModel"
2339    }
2340}
2341workerPort.onmessage = (d: MessageEvents): void => {
2342  console.log("worker.ets onmessage");
2343  let data: string = d.data;
2344  let func1 = () => {
2345    console.log("post message is function");
2346  }
2347  // workerPort.postMessage(func1); A serialization error occurs when passing func1.
2348  let obj2 = new MyModel();
2349  workerPort.postMessage(obj2);     // No serialization error occurs when passing obj2.
2350}
2351workerPort.onmessageerror = () => {
2352    console.log("worker.ets onmessageerror");
2353}
2354workerPort.onerror = (err: ErrorEvent) => {
2355    console.log("worker.ets onerror" + err.message);
2356}
2357```
2358
2359### Memory Model
2360The Worker thread is implemented based on the actor model. In the Worker interaction process, the JS host thread can create multiple Worker threads, each of which are isolated and transfer data through serialization. They complete computing tasks and return the result to the host thread.
2361
2362Each actor concurrently processes tasks of the host thread. For each actor, there is a message queue and a single-thread execution module. The message queue receives requests from the host thread and other actors; the single-thread execution module serially processes requests, sends requests to other actors, and creates new actors. These isolated actors use the asynchronous mode and can run concurrently.
2363
2364## Sample Code
2365> **NOTE**
2366>
2367> Only the FA model is supported in API version 8 and earlier versions. If you want to use API version 8 or earlier, change the API for constructing the Worker instance and the API for creating an object in the Worker thread for communicating with the host thread.<br>
2368### FA Model
2369> The following uses API version 9 as an example.
2370
2371```ts
2372// Main thread (The following assumes that the workers directory and pages directory are at the same level.)
2373import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
2374
2375// Create a Worker instance in the host thread.
2376const workerInstance = new worker.ThreadWorker("workers/worker.ets");
2377
2378// The host thread transfers information to the Worker thread.
2379const buffer = new ArrayBuffer(8);
2380workerInstance.postMessage(buffer, [buffer]);
2381
2382// The host thread receives information from the Worker thread.
2383workerInstance.onmessage = (e: MessageEvents): void => {
2384    // data carries the information sent by the Worker thread.
2385    let data: string = e.data;
2386    console.log("main thread onmessage");
2387
2388    // Terminate the Worker instance.
2389    workerInstance.terminate();
2390}
2391
2392// Call onexit().
2393workerInstance.onexit = (code) => {
2394    console.log("main thread terminate");
2395}
2396
2397workerInstance.onerror = (err: ErrorEvent) => {
2398    console.log("main error message " + err.message);
2399}
2400```
2401```ts
2402// worker.ets
2403import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
2404
2405// Create an object in the Worker thread for communicating with the host thread.
2406const workerPort = worker.workerPort
2407
2408// The Worker thread receives information from the host thread.
2409workerPort.onmessage = (e: MessageEvents): void => {
2410    // data carries the information sent by the host thread.
2411    let data: number = e.data;
2412    const view = new Int8Array(data).fill(3);
2413    console.log("worker.ets onmessage");
2414
2415    // The Worker thread sends information to the host thread.
2416    workerPort.postMessage(view);
2417}
2418
2419// Trigger a callback when an error occurs in the Worker thread.
2420workerPort.onerror = (err: ErrorEvent) => {
2421    console.log("worker.ets onerror");
2422}
2423```
2424Add the following configuration to the module-level **entry/build-profile.json5** file:
2425```json
2426  "buildOption": {
2427    "sourceOption": {
2428      "workers": [
2429        "./src/main/ets/entryability/workers/worker.ets"
2430      ]
2431    }
2432  }
2433```
2434### Stage Model
2435> The following uses API version 12 as an example.
2436```ts
2437// Index.ets
2438import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
2439
2440@Entry
2441@Component
2442struct Index {
2443  @State message: string = 'Hello World';
2444  build() {
2445    Row() {
2446      Column() {
2447        Text(this.message)
2448          .fontSize(50)
2449          .fontWeight(FontWeight.Bold)
2450          .onClick(() => {
2451            // Create a Worker instance in the host thread.
2452            const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
2453            // The host thread transfers information to the Worker thread.
2454            const buffer = new ArrayBuffer(8);
2455            workerInstance.postMessage(buffer);
2456            // The host thread receives information from the Worker thread.
2457            workerInstance.onmessage = (e: MessageEvents): void => {
2458              // data carries the information sent by the Worker thread.
2459              let data: number = e.data;
2460              console.info("main thread data is  " + data);
2461              // Terminate the Worker instance.
2462              workerInstance.terminate();
2463            }
2464            // Call onexit().
2465            workerInstance.onexit = (code) => {
2466              console.log("main thread terminate");
2467            }
2468
2469            workerInstance.onerror = (err: ErrorEvent) => {
2470              console.log("main error message " + err.message);
2471            }
2472          })
2473      }
2474      .width('100%')
2475      .height('100%')
2476    }
2477  }
2478}
2479```
2480```ts
2481// Worker.ets
2482import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS';
2483
2484// Create an object in the Worker thread for communicating with the host thread.
2485const workerPort = worker.workerPort
2486
2487// The Worker thread receives information from the host thread.
2488workerPort.onmessage = (e: MessageEvents): void => {
2489  // data carries the information sent by the host thread.
2490  let data: number = e.data;
2491  // Write data to the received buffer.
2492  const view = new Int8Array(data).fill(3);
2493  // The Worker thread sends information to the host thread.
2494  workerPort.postMessage(view);
2495}
2496
2497// Trigger a callback when an error occurs in the Worker thread.
2498workerPort.onerror = (err: ErrorEvent) => {
2499  console.log("worker.ets onerror" + err.message);
2500}
2501```
2502Add the following configuration to the module-level **entry/build-profile.json5** file:
2503```json
2504  "buildOption": {
2505    "sourceOption": {
2506      "workers": [
2507        "./src/main/ets/workers/Worker.ets"
2508      ]
2509    }
2510  }
2511```
2512<!--no_check-->
2513