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