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