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