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```ts 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```ts 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.ts", {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.ts"); 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 a child 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 a child 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/entryability/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 166Used by the host thread to send a message to the worker thread by transferring object ownership. 167 168**System capability**: SystemCapability.Utils.Lang 169 170**Parameters** 171 172| Name | Type | Mandatory| Description | 173| -------- | ------------- | ---- | ------------------------------------------------------------ | 174| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 175| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the worker thread. After the transfer, the objects are available only in the worker thread. The array cannot be null.| 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 | An exception occurred during serialization. | 185 186**Example** 187 188```ts 189const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 190 191let buffer = new ArrayBuffer(8); 192workerInstance.postMessage(buffer, [buffer]); 193``` 194 195### postMessage<sup>9+</sup> 196 197postMessage(message: Object, options?: PostMessageOptions): void 198 199Used by the host thread to send a message to the worker thread by transferring object ownership or copying data. 200 201**System capability**: SystemCapability.Utils.Lang 202 203**Parameters** 204 205| Name | Type | Mandatory| Description | 206| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 207| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 208| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the worker thread and becomes unavailable in the host thread. The objects are available only in the worker thread.<br>If this parameter is not specified, the default value **undefined** is used, and information is transferred to the worker thread by copying data.| 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 | An exception occurred during serialization. | 218 219**Example** 220 221```ts 222const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 223 224workerInstance.postMessage("hello world"); 225 226let 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```ts 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```ts 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```ts 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```ts 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```ts 381const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 382workerInstance.onexit = () => { 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//workerPort.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```ts 421const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 422workerInstance.onerror = () => { 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 **workerPort.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```ts 454import worker, { MessageEvents } from '@ohos.worker'; 455 456const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 457workerInstance.onmessage = (e: MessageEvents): void => { 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```ts 491const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 492workerInstance.onmessageerror= () => { 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```ts 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```ts 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```ts 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```ts 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 = (e: MessageEvents): void => { 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```ts 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```ts 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```ts 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```ts 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```ts 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 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 = (e: MessageEvents): void => { 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```ts 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 854Used by the worker thread to send a message to the host thread by transferring object ownership. 855 856**System capability**: SystemCapability.Utils.Lang 857 858**Parameters** 859 860| Name | Type | Mandatory| Description | 861| -------- | ------------- | ---- | ------------------------------------------------------------ | 862| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 863| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null.| 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 | An exception occurred during serialization. | 873 874**Example** 875 876```ts 877// Main thread 878import worker from '@ohos.worker'; 879const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 880workerInstance.postMessage("hello world"); 881workerInstance.onmessage = (e: MessageEvents): void => { 882 console.log("receive data from worker.ts"); 883} 884``` 885 886```ts 887// worker.ts 888import worker from '@ohos.worker'; 889const workerPort = worker.workerPort; 890workerPort.onmessage = (e: MessageEvents): void => { 891 let 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 900Used by the worker thread to send a message to the host thread by transferring object ownership or copying data. 901 902**System capability**: SystemCapability.Utils.Lang 903 904**Parameters** 905 906| Name | Type | Mandatory| Description | 907| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 908| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 909| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the host thread and becomes unavailable in the worker thread. The objects are available only in the host thread.<br>If this parameter is not specified, the default value **undefined** is used, and information is transferred to the host thread by copying data.| 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 | An exception occurred during serialization. | 919 920**Example** 921 922```ts 923// Main thread 924import worker from '@ohos.worker'; 925const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 926workerInstance.postMessage("hello world"); 927workerInstance.onmessage = (e: MessageEvents): void => { 928 console.log("receive data from worker.ts"); 929} 930``` 931 932```ts 933// worker.ts 934import worker from '@ohos.worker'; 935const workerPort = worker.workerPort; 936workerPort.onmessage = (e: MessageEvents): void => { 937 workerPort.postMessage("receive data from main thread"); 938} 939``` 940 941 942### close<sup>9+</sup> 943 944close(): void 945 946Terminates the worker thread to stop it from receiving messages. 947 948**System capability**: SystemCapability.Utils.Lang 949 950**Error codes** 951 952For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 953 954| ID| Error Message | 955| -------- | ------------------------------- | 956| 10200004 | Worker instance is not running. | 957 958**Example** 959 960```ts 961// Main thread 962import worker from '@ohos.worker'; 963const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 964``` 965 966```ts 967// worker.ts 968import worker from '@ohos.worker'; 969const workerPort = worker.workerPort; 970workerPort.onmessage = (e: MessageEvents): void => { 971 workerPort.close() 972} 973``` 974 975 976### onmessage<sup>9+</sup> 977 978onmessage?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) => void 979 980Defines 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. 981 982**System capability**: SystemCapability.Utils.Lang 983 984**Parameters** 985 986| Name| Type | Mandatory| Description | 987| ------ | ---------------------------------------------------- | ---- | ------------------------ | 988| this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | 989| ev | [MessageEvents](#messageevents9) | Yes | Message received.| 990 991**Error codes** 992 993For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 994 995| ID| Error Message | 996| -------- | -------------------------------------------- | 997| 10200004 | Worker instance is not running. | 998| 10200005 | The invoked API is not supported in workers. | 999 1000**Example** 1001 1002```ts 1003// Main thread 1004import worker from '@ohos.worker'; 1005const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 1006workerInstance.postMessage("hello world"); 1007``` 1008 1009```ts 1010// worker.ts 1011import worker from '@ohos.worker'; 1012const workerPort = worker.workerPort; 1013workerPort.onmessage = (e: MessageEvents): void => { 1014 console.log("receive main thread message"); 1015} 1016``` 1017 1018 1019### onmessageerror<sup>9+</sup> 1020 1021onmessageerror?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) => void 1022 1023Defines 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. 1024 1025**System capability**: SystemCapability.Utils.Lang 1026 1027**Parameters** 1028 1029| Name| Type | Mandatory| Description | 1030| ------ | -------------------------------- | ---- | ---------- | 1031| this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | 1032| ev | [MessageEvents](#messageevents9) | Yes | Error data.| 1033 1034**Error codes** 1035 1036For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 1037 1038| ID| Error Message | 1039| -------- | -------------------------------------------- | 1040| 10200004 | Worker instance is not running. | 1041| 10200005 | The invoked API is not supported in workers. | 1042 1043**Example** 1044 1045```ts 1046// Main thread 1047import worker from '@ohos.worker'; 1048const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 1049``` 1050 1051```ts 1052// worker.ts 1053import worker from '@ohos.worker'; 1054const workerPort = worker.workerPort; 1055workerPort.onmessageerror = () => { 1056 console.log("worker.ts onmessageerror") 1057} 1058``` 1059 1060 1061## WorkerEventListener<sup>9+</sup> 1062 1063(event: Event): void | Promise<void> 1064 1065Implements event listening. 1066 1067**System capability**: SystemCapability.Utils.Lang 1068 1069**Parameters** 1070 1071| Name| Type | Mandatory| Description | 1072| ------ | --------------- | ---- | -------------- | 1073| event | [Event](#event) | Yes | Event class for the callback to invoke.| 1074 1075**Return value** 1076 1077| Type | Description | 1078| ------------------------------------- | ------------------------------- | 1079| void \| Promise<void> | Returns no value or returns a **Promise**.| 1080 1081**Error codes** 1082 1083For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). 1084 1085| ID| Error Message | 1086| -------- | -------------------------------------------- | 1087| 10200004 | Worker instance is not running. | 1088| 10200005 | The invoked API is not supported in workers. | 1089 1090**Example** 1091 1092```ts 1093const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); 1094workerInstance.addEventListener("alert", ()=>{ 1095 console.log("alert listener callback"); 1096}) 1097``` 1098 1099 1100## GlobalScope<sup>9+</sup> 1101 1102Implements the running environment of the worker thread. The **GlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9). 1103 1104### Attributes 1105 1106**System capability**: SystemCapability.Utils.Lang 1107 1108| Name| Type | Readable| Writable| Description | 1109| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- | 1110| name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| 1111| self | [GlobalScope](#globalscope9) & typeof globalThis | Yes | No | **GlobalScope** itself. | 1112 1113 1114### onerror<sup>9+</sup> 1115 1116onerror?: (ev: ErrorEvent) => void 1117 1118Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. 1119 1120**System capability**: SystemCapability.Utils.Lang 1121 1122**Parameters** 1123 1124| Name| Type | Mandatory| Description | 1125| ------ | ------------------------- | ---- | ---------- | 1126| ev | [ErrorEvent](#errorevent) | Yes | Error data.| 1127 1128**Example** 1129 1130```ts 1131// Main thread 1132import worker from '@ohos.worker'; 1133const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") 1134``` 1135 1136```ts 1137// worker.ts 1138import worker from '@ohos.worker'; 1139const workerPort = worker.workerPort 1140workerPort.onerror = () => { 1141 console.log("worker.ts onerror") 1142} 1143``` 1144 1145## MessageEvents<sup>9+</sup> 1146 1147Holds the data transferred between worker threads. 1148 1149**System capability**: SystemCapability.Utils.Lang 1150 1151| Name| Type| Readable| Writable| Description | 1152| ---- | ---- | ---- | ---- | ------------------ | 1153| data | any | Yes | No | Data transferred between threads.| 1154 1155## Worker<sup>(deprecated)</sup> 1156 1157 1158Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget). 1159 1160> **NOTE**<br> 1161> 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. 1162 1163### constructor<sup>(deprecated)</sup> 1164 1165constructor(scriptURL: string, options?: WorkerOptions) 1166 1167A constructor used to create a **Worker** instance. 1168 1169> **NOTE**<br> 1170> 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. 1171 1172**System capability**: SystemCapability.Utils.Lang 1173 1174**Parameters** 1175 1176| Name | Type | Mandatory| Description | 1177| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | 1178| 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.| 1179| options | [WorkerOptions](#workeroptions) | No | Options that can be set for the **Worker** instance. | 1180 1181**Return value** 1182 1183| Type | Description | 1184| ------ | --------------------------------------------------------- | 1185| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.| 1186 1187**Example** 1188 1189```ts 1190import worker from '@ohos.worker'; 1191// Create a Worker instance. 1192 1193// In the FA model, the workers directory is at the same level as the pages directory. 1194const workerFAModel01 = new worker.Worker("workers/worker.ts", {name:"first worker in FA model"}); 1195// In the FA model, the workers directory is at the same level as the parent directory of the pages directory. 1196const workerFAModel02 = new worker.Worker("../workers/worker.ts"); 1197 1198// In the stage model, the workers directory is at the same level as the pages directory. 1199const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"}); 1200// In the stage model, the workers directory is a child directory of the pages directory. 1201const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts'); 1202 1203// For the script URL "entry/ets/workers/worker.ts" in the stage model: 1204// entry is the value of the name attribute under module in the module.json5 file. 1205// ets indicates the programming language in use. 1206``` 1207Depending 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. 1208 1209(1) The **workers** directory and **pages** directory are at the same level. 1210 1211In the FA model: 1212 1213```json 1214 "buildOption": { 1215 "sourceOption": { 1216 "workers": [ 1217 "./src/main/ets/entryability/workers/worker.ts" 1218 ] 1219 } 1220 } 1221``` 1222In the stage model: 1223```json 1224 "buildOption": { 1225 "sourceOption": { 1226 "workers": [ 1227 "./src/main/ets/workers/worker.ts" 1228 ] 1229 } 1230 } 1231``` 1232(2) The **workers** directory and **pages** directory are at different levels. 1233 1234In the FA model: 1235```json 1236 "buildOption": { 1237 "sourceOption": { 1238 "workers": [ 1239 "./src/main/ets/workers/worker.ts" 1240 ] 1241 } 1242 } 1243``` 1244In the stage model: 1245```json 1246 "buildOption": { 1247 "sourceOption": { 1248 "workers": [ 1249 "./src/main/ets/pages/workers/worker.ts" 1250 ] 1251 } 1252 } 1253``` 1254 1255### postMessage<sup>(deprecated)</sup> 1256 1257postMessage(message: Object, transfer: ArrayBuffer[]): void 1258 1259Used by the host thread to send a message to the worker thread by transferring object ownership. 1260 1261> **NOTE**<br> 1262> 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. 1263 1264**System capability**: SystemCapability.Utils.Lang 1265 1266**Parameters** 1267 1268| Name | Type | Mandatory| Description | 1269| -------- | ------------- | ---- | ------------------------------------------------------------ | 1270| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 1271| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the worker thread. After the transfer, the objects are available only in the worker thread. The array cannot be null.| 1272 1273**Example** 1274 1275```ts 1276const workerInstance = new worker.Worker("workers/worker.ts"); 1277 1278let buffer = new ArrayBuffer(8); 1279workerInstance.postMessage(buffer, [buffer]); 1280``` 1281 1282### postMessage<sup>(deprecated)</sup> 1283 1284postMessage(message: Object, options?: PostMessageOptions): void 1285 1286Used by the host thread to send a message to the worker thread by transferring object ownership or copying data. 1287 1288> **NOTE**<br> 1289> 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. 1290 1291**System capability**: SystemCapability.Utils.Lang 1292 1293**Parameters** 1294 1295| Name | Type | Mandatory| Description | 1296| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1297| message | Object | Yes | Data to be sent to the worker thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 1298| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the worker thread and becomes unavailable in the host thread. The objects are available only in the worker thread.<br>If this parameter is not specified, the default value **undefined** is used, and information is transferred to the worker thread by copying data.| 1299 1300**Example** 1301 1302```ts 1303const workerInstance = new worker.Worker("workers/worker.ts"); 1304 1305workerInstance.postMessage("hello world"); 1306 1307let buffer = new ArrayBuffer(8); 1308workerInstance.postMessage(buffer, [buffer]); 1309``` 1310 1311 1312### on<sup>(deprecated)</sup> 1313 1314on(type: string, listener: EventListener): void 1315 1316Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener<sup>(deprecated)</sup>](#addeventlistenerdeprecated). 1317 1318> **NOTE**<br> 1319> 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. 1320 1321**System capability**: SystemCapability.Utils.Lang 1322 1323**Parameters** 1324 1325| Name | Type | Mandatory| Description | 1326| -------- | ------------------------------- | ---- | ---------------- | 1327| type | string | Yes | Type of the event to listen for.| 1328| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | 1329 1330**Example** 1331 1332```ts 1333const workerInstance = new worker.Worker("workers/worker.ts"); 1334workerInstance.on("alert", ()=>{ 1335 console.log("alert listener callback"); 1336}) 1337``` 1338 1339 1340### once<sup>(deprecated)</sup> 1341 1342once(type: string, listener: EventListener): void 1343 1344Adds an event listener for the worker thread and removes the event listener after it is invoked once. 1345 1346> **NOTE**<br> 1347> 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. 1348 1349**System capability**: SystemCapability.Utils.Lang 1350 1351**Parameters** 1352 1353| Name | Type | Mandatory| Description | 1354| -------- | ------------------------------- | ---- | ---------------- | 1355| type | string | Yes | Type of the event to listen for.| 1356| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | 1357 1358**Example** 1359 1360```ts 1361const workerInstance = new worker.Worker("workers/worker.ts"); 1362workerInstance.once("alert", (e)=>{ 1363 console.log("alert listener callback"); 1364}) 1365``` 1366 1367 1368### off<sup>(deprecated)</sup> 1369 1370off(type: string, listener?: EventListener): void 1371 1372Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener<sup>(deprecated)</sup>](#removeeventlistenerdeprecated). 1373 1374> **NOTE**<br> 1375> 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. 1376 1377**System capability**: SystemCapability.Utils.Lang 1378 1379**Parameters** 1380 1381| Name | Type | Mandatory| Description | 1382| -------- | ------------------------------- | ---- | -------------------- | 1383| type | string | Yes | Type of the event for which the event listener is to be removed.| 1384| listener | [EventListener](#eventlistener) | No | Callback of the event listener to remove. | 1385 1386**Example** 1387 1388```ts 1389const workerInstance = new worker.Worker("workers/worker.ts"); 1390// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. 1391workerInstance.off("alert"); 1392``` 1393 1394 1395### terminate<sup>(deprecated)</sup> 1396 1397terminate(): void 1398 1399Terminates the worker thread to stop it from receiving messages. 1400 1401> **NOTE**<br> 1402> 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. 1403 1404**System capability**: SystemCapability.Utils.Lang 1405 1406**Example** 1407 1408```ts 1409const workerInstance = new worker.Worker("workers/worker.ts"); 1410workerInstance.terminate(); 1411``` 1412 1413 1414### onexit<sup>(deprecated)</sup> 1415 1416onexit?: (code: number) => void 1417 1418Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread. 1419 1420> **NOTE**<br> 1421> 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. 1422 1423**System capability**: SystemCapability.Utils.Lang 1424 1425**Parameters** 1426 1427| Name| Type | Mandatory| Description | 1428| ------ | ------ | ---- | ------------------ | 1429| code | number | Yes | Code indicating the worker thread exit state.| 1430 1431**Example** 1432 1433```ts 1434const workerInstance = new worker.Worker("workers/worker.ts"); 1435workerInstance.onexit = () => { 1436 console.log("onexit"); 1437} 1438 1439// onexit is executed in either of the following ways: 1440// Main thread: 1441workerInstance.terminate(); 1442 1443// Worker thread: 1444//parentPort.close() 1445``` 1446 1447 1448### onerror<sup>(deprecated)</sup> 1449 1450onerror?: (err: ErrorEvent) => void 1451 1452Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread. 1453 1454> **NOTE**<br> 1455> 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. 1456 1457**System capability**: SystemCapability.Utils.Lang 1458 1459**Parameters** 1460 1461| Name| Type | Mandatory| Description | 1462| ------ | ------------------------- | ---- | ---------- | 1463| err | [ErrorEvent](#errorevent) | Yes | Error data.| 1464 1465**Example** 1466 1467```ts 1468const workerInstance = new worker.Worker("workers/worker.ts"); 1469workerInstance.onerror = function() { 1470 console.log("onerror"); 1471} 1472``` 1473 1474 1475### onmessage<sup>(deprecated)</sup> 1476 1477onmessage?: (event: MessageEvent) => void 1478 1479Defines 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. 1480 1481> **NOTE**<br> 1482> 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. 1483 1484**System capability**: SystemCapability.Utils.Lang 1485 1486**Parameters** 1487 1488| Name| Type | Mandatory| Description | 1489| ------ | ------------------------------ | ---- | ---------------------- | 1490| event | [MessageEvent](#messageeventt)| Yes | Message received.| 1491 1492**Example** 1493 1494```ts 1495const workerInstance = new worker.Worker("workers/worker.ts"); 1496workerInstance.onmessage = (e: MessageEvents): void => { 1497 console.log("onmessage"); 1498} 1499``` 1500 1501 1502### onmessageerror<sup>(deprecated)</sup> 1503 1504onmessageerror?: (event: MessageEvent) => void 1505 1506Defines 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. 1507 1508> **NOTE**<br> 1509> 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. 1510 1511**System capability**: SystemCapability.Utils.Lang 1512 1513**Parameters** 1514 1515| Name| Type | Mandatory| Description | 1516| ------ | ------------------------------ | ---- | ---------- | 1517| event | [MessageEvent](#messageeventt)| Yes | Error data.| 1518 1519**Example** 1520 1521```ts 1522const workerInstance = new worker.Worker("workers/worker.ts"); 1523workerInstance.onmessageerror= () => { 1524 console.log("onmessageerror"); 1525} 1526``` 1527 1528 1529## EventTarget<sup>(deprecated)</sup> 1530> **NOTE**<br> 1531> 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. 1532 1533### addEventListener<sup>(deprecated)</sup> 1534 1535addEventListener(type: string, listener: EventListener): void 1536 1537Adds an event listener for the worker thread. This API provides the same functionality as [on<sup>(deprecated)</sup>](#ondeprecated). 1538 1539> **NOTE**<br> 1540> 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. 1541 1542**System capability**: SystemCapability.Utils.Lang 1543 1544**Parameters** 1545 1546| Name | Type | Mandatory| Description | 1547| -------- | ------------------------------- | ---- | ---------------- | 1548| type | string | Yes | Type of the event to listen for.| 1549| listener | [EventListener](#eventlistener) | Yes | Callback to invoke when an event of the specified type occurs. | 1550 1551**Example** 1552 1553```ts 1554const workerInstance = new worker.Worker("workers/worker.ts"); 1555workerInstance.addEventListener("alert", ()=>{ 1556 console.log("alert listener callback"); 1557}) 1558``` 1559 1560 1561### removeEventListener<sup>(deprecated)</sup> 1562 1563removeEventListener(type: string, callback?: EventListener): void 1564 1565Removes an event listener for the worker thread. This API provides the same functionality as [off<sup>(deprecated)</sup>](#offdeprecated). 1566 1567> **NOTE**<br> 1568> 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. 1569 1570**System capability**: SystemCapability.Utils.Lang 1571 1572**Parameters** 1573 1574| Name | Type | Mandatory| Description | 1575| -------- | ------------------------------- | ---- | ------------------------ | 1576| type | string | Yes | Type of the event for which the event listener is to be removed.| 1577| callback | [EventListener](#eventlistener) | No | Callback of the event listener to remove. | 1578 1579**Example** 1580 1581```ts 1582const workerInstance = new worker.Worker("workers/worker.ts"); 1583workerInstance.addEventListener("alert", ()=>{ 1584 console.log("alert listener callback"); 1585}) 1586workerInstance.removeEventListener("alert"); 1587``` 1588 1589 1590### dispatchEvent<sup>(deprecated)</sup> 1591 1592dispatchEvent(event: Event): boolean 1593 1594Dispatches the event defined for the worker thread. 1595 1596> **NOTE**<br> 1597> 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. 1598 1599**System capability**: SystemCapability.Utils.Lang 1600 1601**Parameters** 1602 1603| Name| Type | Mandatory| Description | 1604| ------ | --------------- | ---- | ---------------- | 1605| event | [Event](#event) | Yes | Event to dispatch.| 1606 1607**Return value** 1608 1609| Type | Description | 1610| ------- | ------------------------------- | 1611| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| 1612 1613**Example** 1614 1615```ts 1616const workerInstance = new worker.Worker("workers/worker.ts"); 1617 1618workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet. 1619``` 1620 1621The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows: 1622 1623```ts 1624const workerInstance = new worker.Worker("workers/worker.ts"); 1625 1626// Usage 1: 1627workerInstance.on("alert_on", (e)=>{ 1628 console.log("alert listener callback"); 1629}) 1630workerInstance.once("alert_once", (e)=>{ 1631 console.log("alert listener callback"); 1632}) 1633workerInstance.addEventListener("alert_add", (e)=>{ 1634 console.log("alert listener callback"); 1635}) 1636 1637// The event listener created by once is removed after being executed once. 1638workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. 1639// The event listener created by on will not be proactively deleted. 1640workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); 1641workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); 1642// The event listener created by addEventListener will not be proactively deleted. 1643workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); 1644workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); 1645 1646// Usage 2: 1647// The event type can be customized, and the special types "message", "messageerror", and "error" exist. 1648// When type = "message", the event handler defined by onmessage will also be executed. 1649// When type = "messageerror", the event handler defined by onmessageerror will also be executed. 1650// When type = "error", the event handler defined by onerror will also be executed. 1651// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. 1652 1653workerInstance.addEventListener("message", (e)=>{ 1654 console.log("message listener callback"); 1655}) 1656workerInstance.onmessage = function(e) { 1657 console.log("onmessage : message listener callback"); 1658} 1659// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. 1660workerInstance.dispatchEvent({type:"message", timeStamp:0}); 1661``` 1662### removeAllListener<sup>(deprecated)</sup> 1663 1664removeAllListener(): void 1665 1666Removes all event listeners for the worker thread. 1667 1668> **NOTE**<br> 1669> 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. 1670 1671**System capability**: SystemCapability.Utils.Lang 1672 1673**Example** 1674 1675```ts 1676const workerInstance = new worker.Worker("workers/worker.ts"); 1677workerInstance.addEventListener("alert", (e)=>{ 1678 console.log("alert listener callback"); 1679}) 1680workerInstance.removeAllListener(); 1681``` 1682 1683 1684## DedicatedWorkerGlobalScope<sup>(deprecated)</sup> 1685 1686Implements 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). 1687 1688> **NOTE**<br> 1689> 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. 1690 1691### postMessage<sup>(deprecated)</sup> 1692 1693postMessage(messageObject: Object, transfer: Transferable[]): void; 1694 1695Used by the worker thread to send a message to the host thread by transferring object ownership. 1696 1697> **NOTE**<br> 1698> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.postMessage<sup>9+</sup>](#postmessage9-2). 1699 1700**System capability**: SystemCapability.Utils.Lang 1701 1702**Parameters** 1703 1704| Name | Type | Mandatory| Description | 1705| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1706| messageObject | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 1707| transfer| Transferable[] | Yes | Currently, this parameter is not supported. | 1708 1709### postMessage<sup>9+</sup> 1710 1711postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; 1712 1713Used by the worker thread to send a message to the host thread by transferring object ownership. 1714 1715> **NOTE** 1716> 1717> The **DedicatedWorkerGlobalScope** class is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.postMessage<sup>9+</sup>](#postmessage9-2). 1718 1719**System capability**: SystemCapability.Utils.Lang 1720 1721**Parameters** 1722 1723| Name | Type | Mandatory| Description | 1724| -------- | ------------- | ---- | ------------------------------------------------------------ | 1725| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 1726| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instance holding an array of objects for which the ownership is transferred to the host thread. After the transfer, the objects are available only in the host thread. The array cannot be null.| 1727 1728**Example** 1729 1730```ts 1731// Main thread 1732import worker from '@ohos.worker'; 1733const workerInstance = new worker.Worker("workers/worker.ts"); 1734workerInstance.postMessage("hello world"); 1735workerInstance.onmessage = (e: MessageEvents): void => { 1736 // let data = e.data; 1737 console.log("receive data from worker.ts"); 1738} 1739``` 1740```ts 1741// worker.ts 1742import worker from '@ohos.worker'; 1743const workerPort = worker.workerPort; 1744workerPort.onmessage = (e: MessageEvents): void => { 1745 // let data = e.data; 1746 let buffer = new ArrayBuffer(5) 1747 workerPort.postMessage(buffer, [buffer]); 1748} 1749``` 1750 1751### postMessage<sup>(deprecated)</sup> 1752 1753postMessage(messageObject: Object, options?: PostMessageOptions): void 1754 1755Used by the worker thread to send a message to the host thread by transferring object ownership or copying data. 1756 1757> **NOTE**<br> 1758> 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). 1759 1760**System capability**: SystemCapability.Utils.Lang 1761 1762**Parameters** 1763 1764| Name | Type | Mandatory| Description | 1765| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 1766| message | Object | Yes | Data to be sent to the host thread. The data object must be sequenceable. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| 1767| options | [PostMessageOptions](#postmessageoptions) | No | If this parameter is specified, it functions the same as **ArrayBuffer[]**. Specifically, the ownership of the objects in the array is transferred to the host thread and becomes unavailable in the worker thread. The objects are available only in the host thread.<br>If this parameter is not specified, the default value **undefined** is used, and information is transferred to the host thread by copying data.| 1768 1769**Example** 1770 1771```ts 1772// Main thread 1773import worker from '@ohos.worker'; 1774const workerInstance = new worker.Worker("workers/worker.ts"); 1775workerInstance.postMessage("hello world"); 1776workerInstance.onmessage = (e: MessageEvents): void => { 1777 // let data = e.data; 1778 console.log("receive data from worker.ts"); 1779} 1780``` 1781```ts 1782// worker.ts 1783import worker from '@ohos.worker'; 1784const parentPort = worker.parentPort; 1785parentPort.onmessage = (e: MessageEvents): void => { 1786 // let data = e.data; 1787 parentPort.postMessage("receive data from main thread"); 1788} 1789``` 1790 1791### close<sup>(deprecated)</sup> 1792 1793close(): void 1794 1795Terminates the worker thread to stop it from receiving messages. 1796 1797> **NOTE**<br> 1798> 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). 1799 1800**System capability**: SystemCapability.Utils.Lang 1801 1802**Example** 1803 1804```ts 1805// Main thread 1806import worker from '@ohos.worker'; 1807const workerInstance = new worker.Worker("workers/worker.ts"); 1808``` 1809```ts 1810// worker.ts 1811import worker from '@ohos.worker'; 1812const parentPort = worker.parentPort; 1813parentPort.onmessage = (e: MessageEvents): void => { 1814 parentPort.close() 1815} 1816``` 1817 1818 1819### onmessage<sup>(deprecated)</sup> 1820 1821onmessage?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void 1822 1823Defines 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. 1824 1825> **NOTE**<br> 1826> 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). 1827 1828**System capability**: SystemCapability.Utils.Lang 1829 1830**Parameters** 1831 1832| Name| Type | Mandatory| Description | 1833| ------ | ------------------------------------------------------------ | ---- | ------------------------ | 1834| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | 1835| ev | [MessageEvent](#messageeventt) | Yes | Message received.| 1836 1837**Example** 1838 1839```ts 1840// Main thread 1841import worker from '@ohos.worker'; 1842const workerInstance = new worker.Worker("workers/worker.ts"); 1843workerInstance.postMessage("hello world"); 1844``` 1845```ts 1846// worker.ts 1847import worker from '@ohos.worker'; 1848const parentPort = worker.parentPort; 1849parentPort.onmessage = (e: MessageEvents): void => { 1850 console.log("receive main thread message"); 1851} 1852``` 1853 1854 1855### onmessageerror<sup>(deprecated)</sup> 1856 1857onmessageerror?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void 1858 1859Defines 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. 1860 1861> **NOTE**<br> 1862> 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). 1863 1864**System capability**: SystemCapability.Utils.Lang 1865 1866**Parameters** 1867 1868| Name| Type | Mandatory| Description | 1869| ------ | ------------------------------ | ---- | ---------- | 1870| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| 1871| ev | [MessageEvent](#messageeventt)| Yes | Error data.| 1872 1873**Example** 1874 1875```ts 1876// Main thread 1877import worker from '@ohos.worker'; 1878const workerInstance = new worker.Worker("workers/worker.ts"); 1879``` 1880```ts 1881// worker.ts 1882import worker from '@ohos.worker'; 1883const parentPort = worker.parentPort; 1884parentPort.onmessageerror = () => { 1885 console.log("worker.ts onmessageerror") 1886} 1887``` 1888 1889 1890## PostMessageOptions 1891 1892Defines the object for which the ownership is to be transferred during data transfer. The object must be an **ArrayBuffer** instance. After the ownership is transferred, the object becomes unavailable in the sender and can be used only in the receiver. 1893 1894**System capability**: SystemCapability.Utils.Lang 1895 1896| Name | Type | Readable| Writable| Description | 1897| -------- | -------- | ---- | ---- | --------------------------------- | 1898| transfer | Object[] | Yes | Yes | **ArrayBuffer** array used to transfer the ownership. The array cannot contain **null**.| 1899 1900 1901## Event 1902 1903Defines the event. 1904 1905**System capability**: SystemCapability.Utils.Lang 1906 1907| Name | Type | Readable| Writable| Description | 1908| --------- | ------ | ---- | ---- | -------------------------------------------- | 1909| type | string | Yes | No | Type of the event. | 1910| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created. This parameter is not supported yet.| 1911 1912 1913## EventListener<sup>(deprecated)</sup> 1914 1915(evt: Event): void | Promise<void> 1916 1917Implements event listening. 1918 1919> **NOTE**<br> 1920> 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. 1921 1922**System capability**: SystemCapability.Utils.Lang 1923 1924**Parameters** 1925 1926| Name| Type | Mandatory| Description | 1927| ------ | --------------- | ---- | -------------- | 1928| evt | [Event](#event) | Yes | Event class for the callback to invoke.| 1929 1930**Return value** 1931 1932| Type | Description | 1933| ------------------------------------- | ------------------------------- | 1934| void \| Promise<void> | Returns no value or returns a **Promise**.| 1935 1936**Example** 1937 1938```ts 1939const workerInstance = new worker.Worker("workers/worker.ts"); 1940workerInstance.addEventListener("alert", ()=>{ 1941 console.log("alert listener callback"); 1942}) 1943``` 1944 1945 1946## ErrorEvent 1947 1948Provides detailed information about the exception that occurs during worker execution. The **ErrorEvent** class inherits from [Event](#event). 1949 1950**System capability**: SystemCapability.Utils.Lang 1951 1952| Name | Type | Readable| Writable| Description | 1953| -------- | ------ | ---- | ---- | -------------------- | 1954| message | string | Yes | No | Information about the exception.| 1955| filename | string | Yes | No | File where the exception is located.| 1956| lineno | number | Yes | No | Serial number of the line where the exception is located. | 1957| colno | number | Yes | No | Serial number of the column where the exception is located. | 1958| error | Object | Yes | No | Type of the exception. | 1959 1960 1961## MessageEvent\<T\> 1962 1963Holds the data transferred between worker threads. 1964 1965**System capability**: SystemCapability.Utils.Lang 1966 1967| Name| Type| Readable| Writable| Description | 1968| ---- | ---- | ---- | ---- | ------------------ | 1969| data | T | Yes | No | Data transferred between threads.| 1970 1971 1972## WorkerGlobalScope<sup>(deprecated)</sup> 1973 1974Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget). 1975 1976> **NOTE**<br> 1977> 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. 1978 1979### Attributes 1980 1981**System capability**: SystemCapability.Utils.Lang 1982 1983| Name| Type | Readable| Writable| Description | 1984| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- | 1985| name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| 1986| self | [WorkerGlobalScope](#workerglobalscope) & typeof globalThis | Yes | No | **WorkerGlobalScope**. | 1987 1988 1989### onerror<sup>(deprecated)</sup> 1990 1991onerror?: (ev: ErrorEvent) => void 1992 1993Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. 1994 1995> **NOTE**<br> 1996> 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). 1997 1998**System capability**: SystemCapability.Utils.Lang 1999 2000**Parameters** 2001 2002| Name| Type | Mandatory| Description | 2003| ------ | ------------------------- | ---- | ---------- | 2004| ev | [ErrorEvent](#errorevent) | Yes | Error data.| 2005 2006**Example** 2007 2008```ts 2009// Main thread 2010import worker from '@ohos.worker'; 2011const workerInstance = new worker.Worker("workers/worker.ts") 2012``` 2013```ts 2014// worker.ts 2015import worker from '@ohos.worker'; 2016const parentPort = worker.parentPort 2017parentPort.onerror = () => { 2018 console.log("worker.ts onerror") 2019} 2020``` 2021 2022 2023## More Information 2024 2025### Sequenceable Data Types 2026 2027The following object types are supported: basic types except Symbol, Date, String, RegExp, Array, Map, Set, Object (simple objects only, for example, objects created using **{}** or **new Object**), ArrayBuffer, and typedArray. (Note that only attributes can be transferred for common objects. Prototypes and methods cannot be transferred.) 2028 2029Exception: 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. 2030> **NOTE**<br> 2031> An FA project of API version 9 is used as an example. 2032 2033```ts 2034// Main thread 2035import worker, { MessageEvents } from '@ohos.worker'; 2036const workerInstance = new worker.ThreadWorker("workers/worker.ts"); 2037workerInstance.postMessage("message from main thread to worker"); 2038workerInstance.onmessage = (d: MessageEvents): void => { 2039 // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method. 2040 let data: string = d.data; 2041} 2042``` 2043```ts 2044// worker.ts 2045import worker, { MessageEvents } from '@ohos.worker'; 2046const workerPort = worker.workerPort; 2047class MyModel { 2048 name = "undefined" 2049 Init() { 2050 this.name = "MyModel" 2051 } 2052} 2053workerPort.onmessage = (d: MessageEvents): void => { 2054 console.log("worker.ts onmessage"); 2055 let data: string = d.data; 2056 let func1 = () => { 2057 console.log("post message is function"); 2058 } 2059 let obj1 = { 2060 "index": 2, 2061 "name1": "zhangshan", 2062 setName() { 2063 this.index = 3; 2064 } 2065 } 2066 let obj2 = new MyModel(); 2067 // workerPort.postMessage(func1); A serialization error occurs when passing func1. 2068 // workerPort.postMessage(obj1); A serialization error occurs when passing obj1. 2069 workerPort.postMessage(obj2); // No serialization error occurs when passing obj2. 2070} 2071workerPort.onmessageerror = () => { 2072 console.log("worker.ts onmessageerror"); 2073} 2074workerPort.onerror = () => { 2075 console.log("worker.ts onerror"); 2076} 2077``` 2078 2079### Memory Model 2080The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through serialization. They complete computing tasks and return the result to the main thread. 2081 2082Each 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. 2083 2084## Sample Code 2085> **NOTE**<br> 2086> 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. 2087### FA Model 2088 2089```ts 2090// Main thread (The following assumes that the workers directory and pages directory are at the same level.) 2091import worker, { MessageEvents } from '@ohos.worker'; 2092// Create a Worker instance in the main thread. 2093const workerInstance = new worker.ThreadWorker("workers/worker.ts"); 2094 2095// The main thread transfers information to the worker thread. 2096workerInstance.postMessage("123"); 2097 2098// The main thread receives information from the worker thread. 2099workerInstance.onmessage = (e: MessageEvents): void => { 2100 // data carries the information sent by the worker thread. 2101 let data: string = e.data; 2102 console.log("main thread onmessage"); 2103 2104 // Terminate the Worker instance. 2105 workerInstance.terminate(); 2106} 2107 2108// Call onexit(). 2109workerInstance.onexit = () => { 2110 console.log("main thread terminate"); 2111} 2112``` 2113```ts 2114// worker.ts 2115import worker, { MessageEvents } from '@ohos.worker'; 2116 2117// Create an object in the worker thread for communicating with the main thread. 2118const workerPort = worker.workerPort 2119 2120// The worker thread receives information from the main thread. 2121workerPort.onmessage = (e: MessageEvents): void => { 2122 // data carries the information sent by the main thread. 2123 let data: string = e.data; 2124 console.log("worker.ts onmessage"); 2125 2126 // The worker thread sends information to the main thread. 2127 workerPort.postMessage("123") 2128} 2129 2130// Trigger a callback when an error occurs in the worker thread. 2131workerPort.onerror= () => { 2132 console.log("worker.ts onerror"); 2133} 2134``` 2135Configuration of the **build-profile.json5** file: 2136```json 2137 "buildOption": { 2138 "sourceOption": { 2139 "workers": [ 2140 "./src/main/ets/entryability/workers/worker.ts" 2141 ] 2142 } 2143 } 2144``` 2145### Stage Model 2146```ts 2147// Main thread (The following assumes that the workers directory and pages directory are at different levels.) 2148import worker, { MessageEvents } from '@ohos.worker'; 2149 2150// Create a Worker instance in the main thread. 2151const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts"); 2152 2153// The main thread transfers information to the worker thread. 2154workerInstance.postMessage("123"); 2155 2156// The main thread receives information from the worker thread. 2157workerInstance.onmessage = (e: MessageEvents): void => { 2158 // data carries the information sent by the worker thread. 2159 let data: string = e.data; 2160 console.log("main thread onmessage"); 2161 2162 // Terminate the Worker instance. 2163 workerInstance.terminate(); 2164} 2165// Call onexit(). 2166workerInstance.onexit = () => { 2167 console.log("main thread terminate"); 2168} 2169``` 2170```ts 2171// worker.ts 2172import worker, { MessageEvents } from '@ohos.worker'; 2173 2174// Create an object in the worker thread for communicating with the main thread. 2175const workerPort = worker.workerPort 2176 2177// The worker thread receives information from the main thread. 2178workerPort.onmessage = (e: MessageEvents): void => { 2179 // data carries the information sent by the main thread. 2180 let data: string = e.data; 2181 console.log("worker.ts onmessage"); 2182 2183 // The worker thread sends information to the main thread. 2184 workerPort.postMessage("123") 2185} 2186 2187// Trigger a callback when an error occurs in the worker thread. 2188workerPort.onerror= () => { 2189 console.log("worker.ts onerror"); 2190} 2191``` 2192Configuration of the **build-profile.json5** file: 2193```json 2194 "buildOption": { 2195 "sourceOption": { 2196 "workers": [ 2197 "./src/main/ets/pages/workers/worker.ts" 2198 ] 2199 } 2200 } 2201``` 2202<!--no_check--> 2203