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