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