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