You need to sign in or sign up before continuing.
js-apis-worker.md 80.9 KB
Newer Older
1
# @ohos.worker (Worker Startup)
2 3 4 5

The 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.

With 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.
Z
zengyawen 已提交
6

7 8
The **Context** object of the worker thread is different from that of the main thread. The worker thread does not support UI operations.

G
Gloria 已提交
9 10
> **NOTE**
>
W
wusongqing 已提交
11
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
12

W
wusongqing 已提交
13
## Modules to Import
Z
zengyawen 已提交
14

G
Gloria 已提交
15
```js
Z
zengyawen 已提交
16 17 18
import worker from '@ohos.worker';
```

W
wusongqing 已提交
19 20 21

## Attributes

W
wusongqing 已提交
22 23
**System capability**: SystemCapability.Utils.Lang

24
| Name                             | Type                                                     | Readable| Writable| Description                                                        |
G
Gloria 已提交
25 26
| --------------------------------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| workerPort<sup>9+</sup>           | [ThreadWorkerGlobalScope](#threadworkerglobalscope9)      | Yes  | Yes  | Object of the worker thread used to communicate with the host thread.                        |
27
| parentPort<sup>(deprecated)</sup> | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes  | Yes  | Object of the worker thread used to communicate with the host thread.<br>This attribute is supported since API version 7 and deprecated since API version 9.<br>You are advised to use **workerPort<sup>9+</sup>** instead.|
W
wusongqing 已提交
28 29 30


## WorkerOptions
Z
zengyawen 已提交
31

W
wusongqing 已提交
32 33 34
Provides options that can be set for the **Worker** instance to create.

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
35

G
Gloria 已提交
36
| Name| Type| Readable| Writable| Description|
G
Gloria 已提交
37
| ---- | -------- | ---- | ---- | -------------- |
G
Gloria 已提交
38 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**.|
| name | string   | Yes  | Yes| Name of the worker thread. The default value is **undefined**.|
| shared | boolean | Yes  | Yes| Whether sharing of the **Worker** instance is enabled. Currently, sharing is not supported.|
W
wusongqing 已提交
41 42


G
Gloria 已提交
43
## ThreadWorker<sup>9+</sup>
W
wusongqing 已提交
44

45
Before using the following APIs, you must create a **ThreadWorker** instance. The **ThreadWorker** class inherits from [WorkerEventTarget](#workereventtarget9).
G
Gloria 已提交
46 47 48 49 50

### constructor<sup>9+</sup>

constructor(scriptURL: string, options?: WorkerOptions)

51
A constructor used to create a **ThreadWorker** instance.
G
Gloria 已提交
52 53 54 55 56 57 58 59 60 61 62 63

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name   | Type                           | Mandatory| Description                                                        |
| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
| scriptURL | string                          | Yes  | Directory of the script to be executed by the **Worker** instance.<br>In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:<br>(a) The script directory is at the same level as the **pages** directory.<br>(b) The script directory is at a different level from the **pages** directory.|
| options   | [WorkerOptions](#workeroptions) | No  | Options that can be set for the **Worker** instance.                                          |

**Return value**

64 65 66 67 68 69 70 71 72 73 74 75 76 77
| Type        | Description                                                        |
| ------------ | ------------------------------------------------------------ |
| ThreadWorker | Returns the **ThreadWorker** instance created; returns **undefined** if the **ThreadWorker** instance fails to be created.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message|
| -------- | -------- |
| 10200003 | Worker initialization failure. |
| 10200007 | The worker file patch is invalid path. |


G
Gloria 已提交
78 79 80 81 82 83 84

**Example**

```js
import worker from '@ohos.worker';
// Create a Worker instance.

G
Gloria 已提交
85
// In the FA model, the workers directory is at the same level as the pages directory in the entry module.
86
const workerFAModel01 = new worker.ThreadWorker("workers/worker.ts", {name:"first worker in FA model"});
G
Gloria 已提交
87
// In the FA model, the workers directory is at the same level as the parent directory of the pages directory in the entry module.
88
const workerFAModel02 = new worker.ThreadWorker("../workers/worker.ts");
G
Gloria 已提交
89

G
Gloria 已提交
90
// In the stage model, the workers directory is at the same level as the pages directory in the entry module.
G
Gloria 已提交
91
const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"});
G
Gloria 已提交
92
// In the stage model, the workers directory is at the same level as the parent directory of the pages directory in the entry module.
G
Gloria 已提交
93 94 95
const workerStageModel02 = new worker.ThreadWorker('entry/ets/pages/workers/worker.ts');

// For the script URL "entry/ets/workers/worker.ts" in the stage model:
G
Gloria 已提交
96 97 98 99 100 101 102 103 104 105
// entry is the value of the name attribute under module in the module.json5 file, and ets indicates the programming language in use.
// The script URL is related to the level of the workers directory where the worker file is located and is irrelevant to the file where the new worker is located.

// In the esmodule build scenario of the stage model, the script URL specification @bundle:bundlename/entryname/ets/workerdir/workerfile is added.
// @bundle is a fixed label, bundlename indicates the bundle name, entryname indicates the module name, and ets indicates the programming language in use.
// workerdir indicates the directory where the worker file is located, and workerfile indicates the worker file name.
// In the stage model, the workers directory is at the same level as the pages directory in the entry module, and bundlename is com.example.workerdemo.
const workerStageModel03 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker');
// In the stage model, the workers directory is at the same level as the parent directory of the pages directory in the entry module, and bundlename is com.example.workerdemo.
const workerStageModel04 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker');
G
Gloria 已提交
106 107
```

G
Gloria 已提交
108
Depending on whether the **workers** directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file.
G
Gloria 已提交
109

G
Gloria 已提交
110
(1) The **workers** directory and **pages** directory are at the same level.
G
Gloria 已提交
111 112 113 114 115 116 117

In the FA model:

```json
  "buildOption": {
    "sourceOption": {
      "workers": [
118
        "./src/main/ets/entryability/workers/worker.ts"
G
Gloria 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
      ]
    }
  }
```

In the stage model:

```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/workers/worker.ts"
      ]
    }
  }
```

G
Gloria 已提交
136
(2) The **workers** directory and **pages** directory are at different levels.
G
Gloria 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

In the FA model:

```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/workers/worker.ts"
      ]
    }
  }
```

In the stage model:

```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/pages/workers/worker.ts"
      ]
    }
  }
```

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
### postMessage<sup>9+</sup>

postMessage(message: Object, transfer: ArrayBuffer[]): void;

Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information).

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type         | Mandatory| Description                                                        |
| -------- | ------------- | ---- | ------------------------------------------------------------ |
| message  | Object        | Yes  | Message to be sent to the worker thread.                                        |
| transfer | ArrayBuffer[] | Yes  | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | ----------------------------------------- |
| 10200004 | Worker instance is not running.           |
| 10200006 | Serializing an uncaught exception failed. |

**Example**

```js
G
Gloria 已提交
189
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
190 191 192 193

var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]);
```
G
Gloria 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207

### postMessage<sup>9+</sup>

postMessage(message: Object, options?: PostMessageOptions): void

Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information).

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| message | Object                                    | Yes  | Message to be sent to the worker thread.                                        |
G
Gloria 已提交
208
| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.|
G
Gloria 已提交
209

210 211 212 213 214 215 216 217 218
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | ----------------------------------------- |
| 10200004 | Worker instance is not running.           |
| 10200006 | Serializing an uncaught exception failed. |

G
Gloria 已提交
219 220 221
**Example**

```js
G
Gloria 已提交
222
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
223 224 225 226 227 228 229 230 231 232 233

workerInstance.postMessage("hello world");

var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]);
```

### on<sup>9+</sup>

on(type: string, listener: WorkerEventListener): void

234
Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener<sup>9+</sup>](#addeventlistener9).
G
Gloria 已提交
235 236 237 238 239 240 241 242 243 244

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type                                        | Mandatory| Description                  |
| -------- | -------------------------------------------- | ---- | ---------------------- |
| type     | string                                       | Yes  | Type of the event to listen for.      |
| listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.|

245 246 247 248 249 250 251 252 253
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
254 255 256
**Example**

```js
G
Gloria 已提交
257
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
workerInstance.on("alert", (e)=>{
    console.log("alert listener callback");
})
```


### once<sup>9+</sup>

once(type: string, listener: WorkerEventListener): void

Adds an event listener for the worker thread and removes the event listener after it is invoked once.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type                                        | Mandatory| Description                  |
| -------- | -------------------------------------------- | ---- | ---------------------- |
| type     | string                                       | Yes  | Type of the event to listen for.      |
| listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.|

279 280 281 282 283 284 285 286 287
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
288 289 290
**Example**

```js
G
Gloria 已提交
291
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
292 293 294 295 296 297 298 299 300 301
workerInstance.once("alert", (e)=>{
    console.log("alert listener callback");
})
```


### off<sup>9+</sup>

off(type: string, listener?: WorkerEventListener): void

302
Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener<sup>9+</sup>](#removeeventlistener9).
G
Gloria 已提交
303 304 305 306 307 308 309 310 311 312

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type                                        | Mandatory| Description                        |
| -------- | -------------------------------------------- | ---- | ---------------------------- |
| type     | string                                       | Yes  | Type of the event for which the event listener is to be removed.        |
| listener | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.|

313 314 315 316 317 318 319 320 321
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
322 323 324
**Example**

```js
G
Gloria 已提交
325
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
326
// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener.
G
Gloria 已提交
327 328 329 330 331 332 333 334 335 336 337 338
workerInstance.off("alert");
```


### terminate<sup>9+</sup>

terminate(): void

Terminates the worker thread to stop it from receiving messages.

**System capability**: SystemCapability.Utils.Lang

339 340 341 342 343 344 345 346
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

G
Gloria 已提交
347 348 349
**Example**

```js
G
Gloria 已提交
350
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
workerInstance.terminate();
```


### onexit<sup>9+</sup>

onexit?: (code: number) =&gt; void

Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type  | Mandatory| Description              |
| ------ | ------ | ---- | ------------------ |
367
| code   | number | Yes  | Code indicating the worker thread exit state.|
G
Gloria 已提交
368

369 370 371 372 373 374 375 376 377
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
378 379 380
**Example**

```js
G
Gloria 已提交
381
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
382 383 384
workerInstance.onexit = function(e) {
    console.log("onexit");
}
385 386 387 388 389 390 391

// onexit is executed in either of the following ways:
// Main thread:
workerInstance.terminate();

// Worker thread:
//parentPort.close()
G
Gloria 已提交
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
```


### onerror<sup>9+</sup>

onerror?: (err: ErrorEvent) =&gt; void

Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type                     | Mandatory| Description      |
| ------ | ------------------------- | ---- | ---------- |
407
| err    | [ErrorEvent](#errorevent) | Yes  | Error data.|
G
Gloria 已提交
408

409 410 411 412 413 414 415 416 417
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
418 419 420
**Example**

```js
G
Gloria 已提交
421
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
422 423 424 425 426 427 428 429
workerInstance.onerror = function(e) {
    console.log("onerror");
}
```


### onmessage<sup>9+</sup>

430
onmessage?: (event: MessageEvents) =&gt; void
G
Gloria 已提交
431 432 433 434 435 436 437

Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

438 439 440
| Name| Type                            | Mandatory| Description                  |
| ------ | -------------------------------- | ---- | ---------------------- |
| event  | [MessageEvents](#messageevents9) | Yes  | Message received.|
G
Gloria 已提交
441

442 443 444 445 446 447 448 449 450
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
451 452 453
**Example**

```js
G
Gloria 已提交
454
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
455
workerInstance.onmessage = function(e) {
456
    // e: MessageEvents. The usage is as follows:
G
Gloria 已提交
457 458 459 460 461 462 463 464
    // let data = e.data;
    console.log("onmessage");
}
```


### onmessageerror<sup>9+</sup>

465
onmessageerror?: (event: MessageEvents) =&gt; void
G
Gloria 已提交
466 467 468 469 470 471 472

Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

473 474 475
| Name| Type                            | Mandatory| Description      |
| ------ | -------------------------------- | ---- | ---------- |
| event  | [MessageEvents](#messageevents9) | Yes  | Error data.|
G
Gloria 已提交
476

477 478 479 480 481 482 483 484 485
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
486 487 488
**Example**

```js
G
Gloria 已提交
489
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
490 491 492 493 494
workerInstance.onmessageerror= function(e) {
    console.log("onmessageerror");
}
```

495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
### addEventListener<sup>9+</sup>

addEventListener(type: string, listener: WorkerEventListener): void

Adds an event listener for the worker thread. This API provides the same functionality as [on<sup>9+</sup>](#on9).

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type                                        | Mandatory| Description            |
| -------- | -------------------------------------------- | ---- | ---------------- |
| type     | string                                       | Yes  | Type of the event to listen for.|
| listener | [WorkerEventListener](#workereventlistener9) | Yes  | Callback to invoke when an event of the specified type occurs.    |

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

**Example**

```js
G
Gloria 已提交
522
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


### removeEventListener<sup>9+</sup>

removeEventListener(type: string, callback?: WorkerEventListener): void

Removes an event listener for the worker thread. This API provides the same functionality as [off<sup>9+</sup>](#off9).

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type                                        | Mandatory| Description                        |
| -------- | -------------------------------------------- | ---- | ---------------------------- |
| type     | string                                       | Yes  | Type of the event for which the event listener is to be removed.    |
| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

**Example**

```js
G
Gloria 已提交
555
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
workerInstance.removeEventListener("alert");
```


### dispatchEvent<sup>9+</sup>

dispatchEvent(event: Event): boolean

Dispatches the event defined for the worker thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type           | Mandatory| Description            |
| ------ | --------------- | ---- | ---------------- |
| event  | [Event](#event) | Yes  | Event to dispatch.|

**Return value**

| Type   | Description                           |
| ------- | ------------------------------- |
| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

**Example**

```js
G
Gloria 已提交
594 595 596 597 598 599 600 601 602 603
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");

workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet.
```

The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows:

```js
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");

604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
// Usage 1:
workerInstance.on("alert_on", (e)=>{
    console.log("alert listener callback");
})
workerInstance.once("alert_once", (e)=>{
    console.log("alert listener callback");
})
workerInstance.addEventListener("alert_add", (e)=>{
    console.log("alert listener callback");
})

// The event listener created by once is removed after being executed once.
workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet.
// The event listener created by on will not be proactively deleted.
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
// The event listener created by addEventListener will be always valid and will not be proactively deleted.
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});

// Usage 2:
// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
// When type = "message", the event handler defined by onmessage will also be executed.
// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
// When type = "error", the event handler defined by onerror will also be executed.
// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.

workerInstance.addEventListener("message", (e)=>{
    console.log("message listener callback");
})
workerInstance.onmessage = function(e) {
    console.log("onmessage : message listener callback");
}
// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
workerInstance.dispatchEvent({type:"message", timeStamp:0});
```


### removeAllListener<sup>9+</sup>

removeAllListener(): void

Removes all event listeners for the worker thread.

**System capability**: SystemCapability.Utils.Lang

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

**Example**

```js
G
Gloria 已提交
661
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
662 663 664 665 666
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
workerInstance.removeAllListener();
```
G
Gloria 已提交
667 668 669 670 671 672 673

## WorkerEventTarget<sup>9+</sup>

### addEventListener<sup>9+</sup>

addEventListener(type: string, listener: WorkerEventListener): void

674
Adds an event listener for the worker thread. This API provides the same functionality as [on<sup>9+</sup>](#on9).
G
Gloria 已提交
675 676 677 678 679 680 681 682 683 684

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type                                        | Mandatory| Description            |
| -------- | -------------------------------------------- | ---- | ---------------- |
| type     | string                                       | Yes  | Type of the event to listen for.|
| listener | [WorkerEventListener](#workereventlistener9) | Yes  | Callback to invoke when an event of the specified type occurs.    |

685 686 687 688 689 690 691 692 693
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
694 695 696
**Example**

```js
G
Gloria 已提交
697
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
698 699 700 701 702 703 704 705 706 707
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


### removeEventListener<sup>9+</sup>

removeEventListener(type: string, callback?: WorkerEventListener): void

708
Removes an event listener for the worker thread. This API provides the same functionality as [off<sup>9+</sup>](#off9).
G
Gloria 已提交
709 710 711 712 713 714 715 716

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type                                        | Mandatory| Description                        |
| -------- | -------------------------------------------- | ---- | ---------------------------- |
| type     | string                                       | Yes  | Type of the event for which the event listener is to be removed.    |
G
Gloria 已提交
717
| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.|
718 719 720 721 722 723 724 725

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |
G
Gloria 已提交
726 727 728 729

**Example**

```js
G
Gloria 已提交
730
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
731 732 733
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
G
Gloria 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
workerInstance.removeEventListener("alert");
```


### dispatchEvent<sup>9+</sup>

dispatchEvent(event: Event): boolean

Dispatches the event defined for the worker thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type           | Mandatory| Description            |
| ------ | --------------- | ---- | ---------------- |
| event  | [Event](#event) | Yes  | Event to dispatch.|

**Return value**

| Type   | Description                           |
| ------- | ------------------------------- |
| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|

758 759 760 761 762 763 764 765
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

G
Gloria 已提交
766 767 768
**Example**

```js
G
Gloria 已提交
769 770 771 772 773 774 775 776 777 778
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");

workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet.
```

The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows:

```js
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");

779 780 781 782 783 784 785 786 787 788 789 790
// Usage 1:
workerInstance.on("alert_on", (e)=>{
    console.log("alert listener callback");
})
workerInstance.once("alert_once", (e)=>{
    console.log("alert listener callback");
})
workerInstance.addEventListener("alert_add", (e)=>{
    console.log("alert listener callback");
})

// The event listener created by once is removed after being executed once.
791 792
workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet.
// The event listener created by on will not be proactively deleted.
793 794
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
G
Gloria 已提交
795
// The event listener created by addEventListener will be always valid and will not be proactively deleted.
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});

// Usage 2:
// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
// When type = "message", the event handler defined by onmessage will also be executed.
// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
// When type = "error", the event handler defined by onerror will also be executed.
// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.

workerInstance.addEventListener("message", (e)=>{
    console.log("message listener callback");
})
workerInstance.onmessage = function(e) {
    console.log("onmessage : message listener callback");
}
// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
workerInstance.dispatchEvent({type:"message", timeStamp:0});
G
Gloria 已提交
814 815 816 817 818 819 820 821 822 823 824
```


### removeAllListener<sup>9+</sup>

removeAllListener(): void

Removes all event listeners for the worker thread.

**System capability**: SystemCapability.Utils.Lang

825 826 827 828 829 830 831 832
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

G
Gloria 已提交
833 834 835
**Example**

```js
G
Gloria 已提交
836
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
837 838 839
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
G
Gloria 已提交
840 841 842 843 844 845
workerInstance.removeAllListener();
```


## ThreadWorkerGlobalScope<sup>9+</sup>

846
Implements 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).
G
Gloria 已提交
847

848 849 850 851 852 853 854 855 856 857 858 859
### postMessage<sup>9+</sup>

postMessage(messageObject: Object, transfer: ArrayBuffer[]): void;

Sends a message to the host thread from the worker thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type         | Mandatory| Description                                                   |
| -------- | ------------- | ---- | ------------------------------------------------------- |
G
Gloria 已提交
860
| message  | Object        | Yes  | Message to be sent to the host thread.                                 |
861 862 863 864 865 866 867 868 869 870 871 872 873 874
| transfer | ArrayBuffer[] | Yes  | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | ----------------------------------------- |
| 10200004 | Worker instance is not running.           |
| 10200006 | Serializing an uncaught exception failed. |

**Example**

```js
875
// Main thread
876
import worker from '@ohos.worker';
G
Gloria 已提交
877
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
878 879 880
workerInstance.postMessage("hello world");
workerInstance.onmessage = function(e) {
    // let data = e.data;
881
    console.log("receive data from worker.ts");
882 883 884 885
}
```

```js
G
Gloria 已提交
886
// worker.ts
887 888 889 890 891 892 893 894
import worker from '@ohos.worker';
const workerPort = worker.workerPort;
workerPort.onmessage = function(e){
    // let data = e.data;
    var buffer = new ArrayBuffer(8);
    workerPort.postMessage(buffer, [buffer]);
}
```
G
Gloria 已提交
895 896 897 898 899 900 901 902 903 904 905 906 907

### postMessage<sup>9+</sup>

postMessage(messageObject: Object, options?: PostMessageOptions): void

Sends a message to the host thread from the worker thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
908 909
| message | Object                                    | Yes  | Message to be sent to the host thread.                                      |
| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.|
G
Gloria 已提交
910

911 912 913 914 915 916 917 918 919
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                               |
| -------- | ----------------------------------------- |
| 10200004 | Worker instance is not running.           |
| 10200006 | Serializing an uncaught exception failed. |

G
Gloria 已提交
920 921 922
**Example**

```js
923
// Main thread
G
Gloria 已提交
924
import worker from '@ohos.worker';
G
Gloria 已提交
925
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
926 927 928
workerInstance.postMessage("hello world");
workerInstance.onmessage = function(e) {
    // let data = e.data;
929
    console.log("receive data from worker.ts");
G
Gloria 已提交
930 931 932 933
}
```

```js
G
Gloria 已提交
934
// worker.ts
G
Gloria 已提交
935
import worker from '@ohos.worker';
936 937
const workerPort = worker.workerPort;
workerPort.onmessage = function(e){
G
Gloria 已提交
938
    // let data = e.data;
939
    workerPort.postMessage("receive data from main thread");
G
Gloria 已提交
940 941 942 943 944 945 946 947 948 949 950 951
}
```


### close<sup>9+</sup>

close(): void

Terminates the worker thread to stop it from receiving messages.

**System capability**: SystemCapability.Utils.Lang

952 953 954 955 956 957 958 959
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                     |
| -------- | ------------------------------- |
| 10200004 | Worker instance is not running. |

G
Gloria 已提交
960 961 962
**Example**

```js
963
// Main thread
G
Gloria 已提交
964
import worker from '@ohos.worker';
G
Gloria 已提交
965
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
966 967 968
```

```js
G
Gloria 已提交
969
// worker.ts
G
Gloria 已提交
970
import worker from '@ohos.worker';
971 972 973
const workerPort = worker.workerPort;
workerPort.onmessage = function(e) {
    workerPort.close()
G
Gloria 已提交
974 975 976 977 978 979
}
```


### onmessage<sup>9+</sup>

980
onmessage?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) =&gt; void
G
Gloria 已提交
981 982 983 984 985 986 987

Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

988 989 990
| Name| Type                                                | Mandatory| Description                    |
| ------ | ---------------------------------------------------- | ---- | ------------------------ |
| this   | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes  | Caller.        |
991 992 993 994 995 996 997 998 999 1000
| ev     | [MessageEvents](#messageevents9)                     | Yes  | Message received.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |
G
Gloria 已提交
1001 1002 1003 1004

**Example**

```js
1005
// Main thread
G
Gloria 已提交
1006
import worker from '@ohos.worker';
G
Gloria 已提交
1007
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
1008 1009 1010 1011
workerInstance.postMessage("hello world");
```

```js
G
Gloria 已提交
1012
// worker.ts
G
Gloria 已提交
1013
import worker from '@ohos.worker';
1014 1015
const workerPort = worker.workerPort;
workerPort.onmessage = function(e) {
1016
    console.log("receive main thread message");
G
Gloria 已提交
1017 1018 1019 1020 1021 1022
}
```


### onmessageerror<sup>9+</sup>

1023
onmessageerror?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) =&gt; void
G
Gloria 已提交
1024 1025 1026 1027

Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread.

**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1028

G
Gloria 已提交
1029 1030
**Parameters**

1031 1032 1033
| Name| Type                            | Mandatory| Description      |
| ------ | -------------------------------- | ---- | ---------- |
| this   | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes  | Caller.        |
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
| ev     | [MessageEvents](#messageevents9) | Yes  | Error data.|

**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |
G
Gloria 已提交
1044 1045 1046 1047

**Example**

```js
1048
// Main thread
G
Gloria 已提交
1049
import worker from '@ohos.worker';
G
Gloria 已提交
1050
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
1051 1052 1053
```

```js
G
Gloria 已提交
1054
// worker.ts
G
Gloria 已提交
1055 1056
import worker from '@ohos.worker';
const parentPort = worker.workerPort;
1057
parentPort.onmessageerror = function(e) {
1058
    console.log("worker.ts onmessageerror")
G
Gloria 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
}
```


## WorkerEventListener<sup>9+</sup>

(event: Event): void | Promise&lt;void&gt;

Implements event listening.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type           | Mandatory| Description          |
| ------ | --------------- | ---- | -------------- |
| event  | [Event](#event) | Yes  | Event class for the callback to invoke.|

**Return value**

| Type                                 | Description                           |
| ------------------------------------- | ------------------------------- |
| void&nbsp;\|&nbsp;Promise&lt;void&gt; | Returns no value or returns a **Promise**.|

1083 1084 1085 1086 1087 1088 1089 1090 1091
**Error codes**

For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).

| ID| Error Message                                  |
| -------- | -------------------------------------------- |
| 10200004 | Worker instance is not running.              |
| 10200005 | The invoked API is not supported in workers. |

G
Gloria 已提交
1092 1093 1094
**Example**

```js
G
Gloria 已提交
1095
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts");
G
Gloria 已提交
1096 1097 1098 1099 1100 1101 1102 1103
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


## GlobalScope<sup>9+</sup>

1104
Implements the running environment of the worker thread. The **GlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9).
G
Gloria 已提交
1105 1106 1107 1108 1109

### Attributes

**System capability**: SystemCapability.Utils.Lang

1110
| Name| Type                                                        | Readable| Writable| Description                                 |
G
Gloria 已提交
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
| name | string                                                       | Yes  | No  | **Worker** instance specified when there is a new **Worker** instance.|
| self | [GlobalScope](#globalscope9)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes  | No  | **GlobalScope** itself.                    |


### onerror<sup>9+</sup>

onerror?: (ev: ErrorEvent) =&gt; void

Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name| Type                     | Mandatory| Description      |
| ------ | ------------------------- | ---- | ---------- |
1128
| ev     | [ErrorEvent](#errorevent) | Yes  | Error data.|
G
Gloria 已提交
1129 1130 1131 1132

**Example**

```js
1133
// Main thread
G
Gloria 已提交
1134
import worker from '@ohos.worker';
G
Gloria 已提交
1135
const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts")
G
Gloria 已提交
1136 1137 1138
```

```js
G
Gloria 已提交
1139
// worker.ts
G
Gloria 已提交
1140
import worker from '@ohos.worker';
1141 1142
const workerPort = worker.workerPort
workerPort.onerror = function(e){
1143
    console.log("worker.ts onerror")
G
Gloria 已提交
1144 1145 1146
}
```

1147 1148 1149 1150 1151 1152 1153 1154 1155
## MessageEvents<sup>9+</sup>

Holds the data transferred between worker threads.

**System capability**: SystemCapability.Utils.Lang

| Name| Type| Readable| Writable| Description              |
| ---- | ---- | ---- | ---- | ------------------ |
| data | any  | Yes  | No  | Data transferred between threads.|
G
Gloria 已提交
1156 1157 1158 1159 1160

## Worker<sup>(deprecated)</sup>


Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget).
W
wusongqing 已提交
1161

G
Gloria 已提交
1162
> **NOTE**<br>
1163 1164 1165
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker<sup>9+</sup>](#threadworker9) instead.

### constructor<sup>(deprecated)</sup>
W
wusongqing 已提交
1166 1167 1168 1169 1170

constructor(scriptURL: string, options?: WorkerOptions)

A constructor used to create a **Worker** instance.

1171 1172 1173
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1174 1175
**System capability**: SystemCapability.Utils.Lang

W
wusongqing 已提交
1176 1177
**Parameters**

W
wusongqing 已提交
1178 1179
| Name   | Type                           | Mandatory| Description                                                        |
| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
1180
| scriptURL | string                          | Yes  | Directory of the script to be executed by the **Worker** instance.<br>In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:<br>(a) The script directory is at the same level as the **pages** directory.<br>(b) The script directory is at a different level from the **pages** directory.|
W
wusongqing 已提交
1181
| options   | [WorkerOptions](#workeroptions) | No  | Options that can be set for the **Worker** instance.                                          |
W
wusongqing 已提交
1182 1183 1184

**Return value**

W
wusongqing 已提交
1185 1186 1187
| Type  | Description                                                     |
| ------ | --------------------------------------------------------- |
| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.|
W
wusongqing 已提交
1188 1189 1190

**Example**

G
Gloria 已提交
1191
```js
1192
import worker from '@ohos.worker';
1193
// Create a Worker instance.
G
Gloria 已提交
1194

G
Gloria 已提交
1195
// In the FA model, the workers directory is at the same level as the pages directory.
1196
const workerFAModel01 = new worker.Worker("workers/worker.ts", {name:"first worker in FA model"});
G
Gloria 已提交
1197
// In the FA model, the workers directory is at the same level as the parent directory of the pages directory.
1198
const workerFAModel02 = new worker.Worker("../workers/worker.ts");
G
Gloria 已提交
1199

G
Gloria 已提交
1200
// In the stage model, the workers directory is at the same level as the pages directory.
1201
const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts', {name:"first worker in Stage model"});
G
Gloria 已提交
1202
// In the stage model, the workers directory is at the same level as the child directory of the pages directory.
1203
const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts');
G
Gloria 已提交
1204

1205
// For the script URL "entry/ets/workers/worker.ts" in the stage model:
G
Gloria 已提交
1206 1207 1208
// entry is the value of the name attribute under module in the module.json5 file.
// ets indicates the programming language in use.
```
G
Gloria 已提交
1209
Depending on whether the **workers** directory and **pages** directory are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file.
1210

G
Gloria 已提交
1211
(1) The **workers** directory and **pages** directory are at the same level.
G
Gloria 已提交
1212 1213 1214 1215 1216 1217 1218

In the FA model:

```json
  "buildOption": {
    "sourceOption": {
      "workers": [
1219
        "./src/main/ets/entryability/workers/worker.ts"
G
Gloria 已提交
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
      ]
    }
  }
```
In the stage model:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/workers/worker.ts"
      ]
    }
  }
```
G
Gloria 已提交
1234
(2) The **workers** directory and **pages** directory are at different levels.
1235

G
Gloria 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
In the FA model:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/workers/worker.ts"
      ]
    }
  }
```
In the stage model:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/pages/workers/worker.ts"
      ]
    }
  }
W
wusongqing 已提交
1255
```
1256

G
Gloria 已提交
1257 1258
### postMessage<sup>(deprecated)</sup>

1259
postMessage(message: Object, transfer: ArrayBuffer[]): void;
Z
zengyawen 已提交
1260

1261
Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information).
W
wusongqing 已提交
1262

1263 1264 1265
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1266
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1267

W
wusongqing 已提交
1268 1269
**Parameters**

1270 1271 1272 1273 1274 1275 1276 1277
| Name  | Type         | Mandatory| Description                                           |
| -------- | ------------- | ---- | ----------------------------------------------- |
| message  | Object        | Yes  | Message to be sent to the worker thread.                           |
| transfer | ArrayBuffer[] | Yes  | **ArrayBuffer** instances that can be transferred.|

**Example**

```js
1278
const workerInstance = new worker.Worker("workers/worker.ts");
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296

var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]);
```

### postMessage<sup>(deprecated)</sup>

postMessage(message: Object, options?: PostMessageOptions): void

Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information).

> **NOTE**<br>
> 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.

**System capability**: SystemCapability.Utils.Lang

**Parameters**

W
wusongqing 已提交
1297 1298
| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
1299
| message | Object                                    | Yes  | Message to be sent to the worker thread.                                        |
G
Gloria 已提交
1300
| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.|
W
wusongqing 已提交
1301 1302 1303

**Example**

G
Gloria 已提交
1304
```js
1305
const workerInstance = new worker.Worker("workers/worker.ts");
1306

W
wusongqing 已提交
1307
workerInstance.postMessage("hello world");
G
Gloria 已提交
1308 1309 1310

var buffer = new ArrayBuffer(8);
workerInstance.postMessage(buffer, [buffer]);
W
wusongqing 已提交
1311 1312 1313
```


G
Gloria 已提交
1314 1315
### on<sup>(deprecated)</sup>

W
wusongqing 已提交
1316
on(type: string, listener: EventListener): void
Z
zengyawen 已提交
1317

1318 1319 1320 1321
Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener<sup>(deprecated)</sup>](#addeventlistenerdeprecated).

> **NOTE**<br>
> 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.
W
wusongqing 已提交
1322 1323

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1324

W
wusongqing 已提交
1325 1326
**Parameters**

W
wusongqing 已提交
1327 1328 1329
| Name  | Type                           | Mandatory| Description            |
| -------- | ------------------------------- | ---- | ---------------- |
| type     | string                          | Yes  | Type of the event to listen for.|
G
Gloria 已提交
1330
| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.      |
W
wusongqing 已提交
1331 1332 1333

**Example**

G
Gloria 已提交
1334
```js
1335
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1336 1337 1338 1339 1340 1341
workerInstance.on("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
1342 1343
### once<sup>(deprecated)</sup>

W
wusongqing 已提交
1344
once(type: string, listener: EventListener): void
Z
zengyawen 已提交
1345

G
Gloria 已提交
1346
Adds an event listener for the worker thread and removes the event listener after it is invoked once.
W
wusongqing 已提交
1347

1348 1349 1350
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1351
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1352

W
wusongqing 已提交
1353 1354
**Parameters**

W
wusongqing 已提交
1355 1356 1357
| Name  | Type                           | Mandatory| Description            |
| -------- | ------------------------------- | ---- | ---------------- |
| type     | string                          | Yes  | Type of the event to listen for.|
G
Gloria 已提交
1358
| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.      |
W
wusongqing 已提交
1359 1360 1361

**Example**

G
Gloria 已提交
1362
```js
1363
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1364 1365 1366 1367 1368 1369
workerInstance.once("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
1370 1371
### off<sup>(deprecated)</sup>

W
wusongqing 已提交
1372
off(type: string, listener?: EventListener): void
Z
zengyawen 已提交
1373

1374 1375 1376 1377
Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener<sup>(deprecated)</sup>](#removeeventlistenerdeprecated).

> **NOTE**<br>
> 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.
W
wusongqing 已提交
1378 1379

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1380

W
wusongqing 已提交
1381 1382
**Parameters**

G
Gloria 已提交
1383 1384 1385 1386
| Name  | Type                           | Mandatory| Description                |
| -------- | ------------------------------- | ---- | -------------------- |
| type     | string                          | Yes  | Type of the event for which the event listener is to be removed.|
| listener | [EventListener](#eventlistener) | No  | Callback of the event listener to remove.    |
W
wusongqing 已提交
1387 1388 1389

**Example**

G
Gloria 已提交
1390
```js
1391
const workerInstance = new worker.Worker("workers/worker.ts");
1392
// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener.
W
wusongqing 已提交
1393 1394 1395 1396
workerInstance.off("alert");
```


G
Gloria 已提交
1397 1398
### terminate<sup>(deprecated)</sup>

W
wusongqing 已提交
1399
terminate(): void
Z
zengyawen 已提交
1400

G
Gloria 已提交
1401
Terminates the worker thread to stop it from receiving messages.
W
wusongqing 已提交
1402

1403 1404 1405
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1406
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1407

W
wusongqing 已提交
1408
**Example**
Z
zengyawen 已提交
1409

G
Gloria 已提交
1410
```js
1411
const workerInstance = new worker.Worker("workers/worker.ts");
G
Gloria 已提交
1412
workerInstance.terminate();
W
wusongqing 已提交
1413
```
Z
zengyawen 已提交
1414 1415


G
Gloria 已提交
1416 1417
### onexit<sup>(deprecated)</sup>

W
wusongqing 已提交
1418
onexit?: (code: number) =&gt; void
Z
zengyawen 已提交
1419

G
Gloria 已提交
1420
Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread.
W
wusongqing 已提交
1421

1422 1423 1424
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1425
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1426

W
wusongqing 已提交
1427 1428
**Parameters**

W
wusongqing 已提交
1429 1430
| Name| Type  | Mandatory| Description              |
| ------ | ------ | ---- | ------------------ |
1431
| code   | number | Yes  | Code indicating the worker thread exit state.|
W
wusongqing 已提交
1432 1433 1434

**Example**

G
Gloria 已提交
1435
```js
1436
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1437
workerInstance.onexit = function(e) {
G
Gloria 已提交
1438
    console.log("onexit");
W
wusongqing 已提交
1439
}
1440 1441 1442 1443 1444 1445 1446

// onexit is executed in either of the following ways:
// Main thread:
workerInstance.terminate();

// Worker thread:
//parentPort.close()
W
wusongqing 已提交
1447 1448 1449
```


G
Gloria 已提交
1450 1451
### onerror<sup>(deprecated)</sup>

W
wusongqing 已提交
1452
onerror?: (err: ErrorEvent) =&gt; void
Z
zengyawen 已提交
1453

G
Gloria 已提交
1454
Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread.
W
wusongqing 已提交
1455

1456 1457 1458
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1459
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1460

W
wusongqing 已提交
1461 1462
**Parameters**

W
wusongqing 已提交
1463 1464
| Name| Type                     | Mandatory| Description      |
| ------ | ------------------------- | ---- | ---------- |
1465
| err    | [ErrorEvent](#errorevent) | Yes  | Error data.|
W
wusongqing 已提交
1466 1467 1468

**Example**

G
Gloria 已提交
1469
```js
1470
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1471
workerInstance.onerror = function(e) {
G
Gloria 已提交
1472
    console.log("onerror");
W
wusongqing 已提交
1473 1474 1475 1476
}
```


G
Gloria 已提交
1477 1478
### onmessage<sup>(deprecated)</sup>

1479
onmessage?: (event: MessageEvent) =&gt; void
W
wusongqing 已提交
1480

G
Gloria 已提交
1481
Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread.
W
wusongqing 已提交
1482

1483 1484 1485
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1486
**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1487 1488 1489

**Parameters**

1490 1491
| Name| Type                          | Mandatory| Description                  |
| ------ | ------------------------------ | ---- | ---------------------- |
1492
| event  | [MessageEvent](#messageeventt)| Yes  | Message received.|
W
wusongqing 已提交
1493 1494 1495

**Example**

G
Gloria 已提交
1496
```js
1497
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1498
workerInstance.onmessage = function(e) {
1499
    // e: MessageEvent. The usage is as follows:
G
Gloria 已提交
1500 1501
    // let data = e.data;
    console.log("onmessage");
W
wusongqing 已提交
1502 1503 1504 1505
}
```


G
Gloria 已提交
1506 1507
### onmessageerror<sup>(deprecated)</sup>

1508
onmessageerror?: (event: MessageEvent) =&gt; void
Z
zengyawen 已提交
1509

G
Gloria 已提交
1510
Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread.
W
wusongqing 已提交
1511

1512 1513 1514
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1515
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1516

W
wusongqing 已提交
1517 1518
**Parameters**

1519 1520
| Name| Type                          | Mandatory| Description      |
| ------ | ------------------------------ | ---- | ---------- |
1521
| event  | [MessageEvent](#messageeventt)| Yes  | Error data.|
W
wusongqing 已提交
1522 1523 1524

**Example**

G
Gloria 已提交
1525
```js
1526
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1527
workerInstance.onmessageerror= function(e) {
G
Gloria 已提交
1528
    console.log("onmessageerror");
W
wusongqing 已提交
1529 1530 1531 1532
}
```


G
Gloria 已提交
1533 1534
## EventTarget<sup>(deprecated)</sup>
> **NOTE**<br>
1535
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventTarget<sup>9+</sup>](#workereventtarget9) instead.
W
wusongqing 已提交
1536

G
Gloria 已提交
1537
### addEventListener<sup>(deprecated)</sup>
W
wusongqing 已提交
1538 1539

addEventListener(type: string, listener: EventListener): void
Z
zengyawen 已提交
1540

1541 1542 1543 1544
Adds an event listener for the worker thread. This API provides the same functionality as [on<sup>(deprecated)</sup>](#ondeprecated).

> **NOTE**<br>
> 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.
W
wusongqing 已提交
1545 1546

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1547

W
wusongqing 已提交
1548 1549
**Parameters**

W
wusongqing 已提交
1550 1551 1552 1553
| Name  | Type                           | Mandatory| Description            |
| -------- | ------------------------------- | ---- | ---------------- |
| type     | string                          | Yes  | Type of the event to listen for.|
| listener | [EventListener](#eventlistener) | Yes  | Callback to invoke when an event of the specified type occurs.    |
W
wusongqing 已提交
1554 1555 1556

**Example**

G
Gloria 已提交
1557
```js
1558
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1559 1560 1561 1562 1563 1564
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


G
Gloria 已提交
1565 1566
### removeEventListener<sup>(deprecated)</sup>

W
wusongqing 已提交
1567
removeEventListener(type: string, callback?: EventListener): void
Z
zengyawen 已提交
1568

1569 1570 1571 1572
Removes an event listener for the worker thread. This API provides the same functionality as [off<sup>(deprecated)</sup>](#offdeprecated).

> **NOTE**<br>
> 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.
W
wusongqing 已提交
1573 1574

**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1575

W
wusongqing 已提交
1576 1577
**Parameters**

G
Gloria 已提交
1578 1579
| Name  | Type                           | Mandatory| Description                    |
| -------- | ------------------------------- | ---- | ------------------------ |
1580
| type     | string                          | Yes  | Type of the event for which the event listener is to be removed.|
G
Gloria 已提交
1581
| callback | [EventListener](#eventlistener) | No  | Callback of the event listener to remove.        |
W
wusongqing 已提交
1582 1583 1584

**Example**

G
Gloria 已提交
1585
```js
1586
const workerInstance = new worker.Worker("workers/worker.ts");
1587 1588 1589
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
G
Gloria 已提交
1590
workerInstance.removeEventListener("alert");
W
wusongqing 已提交
1591 1592 1593
```


G
Gloria 已提交
1594 1595
### dispatchEvent<sup>(deprecated)</sup>

W
wusongqing 已提交
1596
dispatchEvent(event: Event): boolean
Z
zengyawen 已提交
1597

G
Gloria 已提交
1598
Dispatches the event defined for the worker thread.
W
wusongqing 已提交
1599

1600 1601 1602
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1603
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1604

W
wusongqing 已提交
1605 1606
**Parameters**

W
wusongqing 已提交
1607 1608 1609
| Name| Type           | Mandatory| Description            |
| ------ | --------------- | ---- | ---------------- |
| event  | [Event](#event) | Yes  | Event to dispatch.|
W
wusongqing 已提交
1610 1611 1612

**Return value**

W
wusongqing 已提交
1613 1614
| Type   | Description                           |
| ------- | ------------------------------- |
W
wusongqing 已提交
1615 1616 1617 1618
| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.|

**Example**

G
Gloria 已提交
1619
```js
1620
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1621

G
Gloria 已提交
1622 1623 1624 1625 1626 1627
workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet.
```

The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows:

```js
1628
const workerInstance = new worker.Worker("workers/worker.ts");
G
Gloria 已提交
1629

1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
// Usage 1:
workerInstance.on("alert_on", (e)=>{
    console.log("alert listener callback");
})
workerInstance.once("alert_once", (e)=>{
    console.log("alert listener callback");
})
workerInstance.addEventListener("alert_add", (e)=>{
    console.log("alert listener callback");
})
W
wusongqing 已提交
1640

1641
// The event listener created by once is removed after being executed once.
1642
workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet.
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
// The event listener created by on will not be proactively deleted.
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_on", timeStamp:0});
// The event listener created by addEventListener will not be proactively deleted.
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});
workerInstance.dispatchEvent({type:"alert_add", timeStamp:0});

// Usage 2:
// The event type can be customized, and the special types "message", "messageerror", and "error" exist.
// When type = "message", the event handler defined by onmessage will also be executed.
// When type = "messageerror", the event handler defined by onmessageerror will also be executed.
// When type = "error", the event handler defined by onerror will also be executed.
// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once.

workerInstance.addEventListener("message", (e)=>{
    console.log("message listener callback");
})
workerInstance.onmessage = function(e) {
    console.log("onmessage : message listener callback");
}
// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked.
workerInstance.dispatchEvent({type:"message", timeStamp:0});
```
G
Gloria 已提交
1666 1667
### removeAllListener<sup>(deprecated)</sup>

W
wusongqing 已提交
1668
removeAllListener(): void
Z
zengyawen 已提交
1669

G
Gloria 已提交
1670
Removes all event listeners for the worker thread.
W
wusongqing 已提交
1671

1672 1673 1674
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1675
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1676

W
wusongqing 已提交
1677
**Example**
Z
zengyawen 已提交
1678

G
Gloria 已提交
1679
```js
1680
const workerInstance = new worker.Worker("workers/worker.ts");
1681 1682 1683
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
G
Gloria 已提交
1684
workerInstance.removeAllListener();
W
wusongqing 已提交
1685
```
Z
zengyawen 已提交
1686 1687


G
Gloria 已提交
1688 1689
## DedicatedWorkerGlobalScope<sup>(deprecated)</sup>

1690
Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. This class inherits from [WorkerGlobalScope](#workerglobalscope).
Z
zengyawen 已提交
1691

1692 1693
> **NOTE**<br>
> 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.
Z
zengyawen 已提交
1694

G
Gloria 已提交
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
### postMessage<sup>(deprecated)</sup>

postMessage(messageObject: Object, transfer: Transferable[]): void;

Sends a message to the host thread from the worker thread.

> **NOTE**<br>
> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.postMessage<sup>9+</sup>](#postmessage9-2).

**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| messageObject | Object                                    | Yes  | Message to be sent to the host thread.                                      |
| transfer| Transferable[]                            | Yes  | Currently, this parameter is not supported.                                        |

1713 1714 1715 1716 1717 1718
### postMessage<sup>9+</sup>

postMessage(messageObject: Object, transfer: ArrayBuffer[]): void;

Sends a message to the host thread from the worker thread.

G
Gloria 已提交
1719 1720 1721 1722
> **NOTE**
>
> The **DedicatedWorkerGlobalScope** class is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.postMessage<sup>9+</sup>](#postmessage9-2).

1723 1724 1725 1726 1727 1728
**System capability**: SystemCapability.Utils.Lang

**Parameters**

| Name  | Type         | Mandatory| Description                                                 |
| -------- | ------------- | ---- | ----------------------------------------------------- |
G
Gloria 已提交
1729
| message  | Object        | Yes  | Message to be sent to the host thread.                               |
1730 1731 1732 1733 1734
| transfer | ArrayBuffer[] | Yes  | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.|

**Example**

```js
1735
// Main thread
1736
import worker from '@ohos.worker';
1737
const workerInstance = new worker.Worker("workers/worker.ts");
1738 1739 1740
workerInstance.postMessage("hello world");
workerInstance.onmessage = function(e) {
    // let data = e.data;
1741
    console.log("receive data from worker.ts");
1742 1743 1744
}
```
```js
1745
// worker.ts
1746 1747 1748 1749 1750 1751 1752 1753 1754
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e){
    // let data = e.data;
    let buffer = new ArrayBuffer(5)
    parentPort.postMessage(buffer, [buffer]);
}
```

G
Gloria 已提交
1755 1756
### postMessage<sup>(deprecated)</sup>

G
Gloria 已提交
1757
postMessage(messageObject: Object, options?: PostMessageOptions): void
Z
zengyawen 已提交
1758

G
Gloria 已提交
1759
Sends a message to the host thread from the worker thread.
W
wusongqing 已提交
1760

1761
> **NOTE**<br>
G
Gloria 已提交
1762
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.postMessage<sup>9+</sup>](#postmessage9-3).
1763

W
wusongqing 已提交
1764
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1765

W
wusongqing 已提交
1766 1767
**Parameters**

W
wusongqing 已提交
1768 1769
| Name | Type                                     | Mandatory| Description                                                        |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
G
Gloria 已提交
1770 1771
| message | Object                                    | Yes  | Message to be sent to the host thread.                                      |
| options | [PostMessageOptions](#postmessageoptions) | No  | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.|
W
wusongqing 已提交
1772 1773 1774

**Example**

G
Gloria 已提交
1775
```js
1776
// Main thread
W
wusongqing 已提交
1777
import worker from '@ohos.worker';
1778
const workerInstance = new worker.Worker("workers/worker.ts");
G
Gloria 已提交
1779
workerInstance.postMessage("hello world");
W
wusongqing 已提交
1780
workerInstance.onmessage = function(e) {
G
Gloria 已提交
1781
    // let data = e.data;
1782
    console.log("receive data from worker.ts");
W
wusongqing 已提交
1783 1784
}
```
G
Gloria 已提交
1785
```js
1786
// worker.ts
W
wusongqing 已提交
1787 1788 1789
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e){
G
Gloria 已提交
1790
    // let data = e.data;
1791
    parentPort.postMessage("receive data from main thread");
W
wusongqing 已提交
1792 1793 1794
}
```

G
Gloria 已提交
1795 1796
### close<sup>(deprecated)</sup>

W
wusongqing 已提交
1797
close(): void
Z
zengyawen 已提交
1798

G
Gloria 已提交
1799
Terminates the worker thread to stop it from receiving messages.
W
wusongqing 已提交
1800

1801
> **NOTE**<br>
G
Gloria 已提交
1802
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.close<sup>9+</sup>](#close9).
1803

W
wusongqing 已提交
1804
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1805

W
wusongqing 已提交
1806 1807
**Example**

G
Gloria 已提交
1808
```js
1809
// Main thread
W
wusongqing 已提交
1810
import worker from '@ohos.worker';
1811
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1812
```
G
Gloria 已提交
1813
```js
1814
// worker.ts
W
wusongqing 已提交
1815 1816 1817 1818 1819 1820 1821 1822
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e) {
    parentPort.close()
}
```


G
Gloria 已提交
1823 1824
### onmessage<sup>(deprecated)</sup>

1825
onmessage?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) =&gt; void
W
wusongqing 已提交
1826

1827
Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread.
W
wusongqing 已提交
1828

1829
> **NOTE**<br>
G
Gloria 已提交
1830
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.onmessage<sup>9+</sup>](#onmessage9-1).
1831

W
wusongqing 已提交
1832
**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1833 1834 1835

**Parameters**

1836 1837 1838
| Name| Type                                                        | Mandatory| Description                    |
| ------ | ------------------------------------------------------------ | ---- | ------------------------ |
| this   | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes  | Caller.        |
1839
| ev     | [MessageEvent](#messageeventt)                              | Yes  | Message received.|
W
wusongqing 已提交
1840 1841 1842

**Example**

G
Gloria 已提交
1843
```js
1844
// Main thread
W
wusongqing 已提交
1845
import worker from '@ohos.worker';
1846
const workerInstance = new worker.Worker("workers/worker.ts");
G
Gloria 已提交
1847
workerInstance.postMessage("hello world");
W
wusongqing 已提交
1848
```
G
Gloria 已提交
1849
```js
1850
// worker.ts
W
wusongqing 已提交
1851 1852 1853
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
parentPort.onmessage = function(e) {
1854
    console.log("receive main thread message");
W
wusongqing 已提交
1855 1856 1857 1858
}
```


G
Gloria 已提交
1859 1860
### onmessageerror<sup>(deprecated)</sup>

1861
onmessageerror?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) =&gt; void
Z
zengyawen 已提交
1862

G
Gloria 已提交
1863
Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread.
W
wusongqing 已提交
1864

1865
> **NOTE**<br>
G
Gloria 已提交
1866
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope<sup>9+</sup>.onmessageerror<sup>9+</sup>](#onmessageerror9-1).
1867

W
wusongqing 已提交
1868
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
1869

W
wusongqing 已提交
1870 1871
**Parameters**

1872 1873 1874
| Name| Type                          | Mandatory| Description      |
| ------ | ------------------------------ | ---- | ---------- |
| this   | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes  | Caller.|
1875
| ev     | [MessageEvent](#messageeventt)| Yes  | Error data.|
W
wusongqing 已提交
1876 1877 1878

**Example**

G
Gloria 已提交
1879
```js
1880
// Main thread
W
wusongqing 已提交
1881
import worker from '@ohos.worker';
1882
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1883
```
G
Gloria 已提交
1884
```js
1885
// worker.ts
W
wusongqing 已提交
1886 1887
import worker from '@ohos.worker';
const parentPort = worker.parentPort;
1888
parentPort.onmessageerror = function(e) {
1889
    console.log("worker.ts onmessageerror")
W
wusongqing 已提交
1890 1891 1892 1893 1894 1895 1896 1897
}
```


## PostMessageOptions

Specifies the object whose ownership needs to be transferred during data transfer. The object must be **ArrayBuffer**.

W
wusongqing 已提交
1898 1899
**System capability**: SystemCapability.Utils.Lang

1900
| Name    | Type    | Readable| Writable| Description                             |
W
wusongqing 已提交
1901
| -------- | -------- | ---- | ---- | --------------------------------- |
G
Gloria 已提交
1902
| transfer | Object[] | Yes  | Yes  | **ArrayBuffer** array used to transfer the ownership. The array cannot contain **null**.|
W
wusongqing 已提交
1903 1904 1905


## Event
Z
zengyawen 已提交
1906 1907 1908

Defines the event.

W
wusongqing 已提交
1909 1910
**System capability**: SystemCapability.Utils.Lang

1911 1912 1913 1914
| Name     | Type  | Readable| Writable| Description                                        |
| --------- | ------ | ---- | ---- | -------------------------------------------- |
| type      | string | Yes  | No  | Type of the event.                            |
| timeStamp | number | Yes  | No  | Timestamp (accurate to millisecond) when the event is created. This parameter is not supported yet.|
W
wusongqing 已提交
1915 1916


G
Gloria 已提交
1917 1918
## EventListener<sup>(deprecated)</sup>

1919
(evt: Event): void | Promise&lt;void&gt;
Z
zengyawen 已提交
1920

1921
Implements event listening.
Z
zengyawen 已提交
1922

1923 1924 1925
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1926 1927
**System capability**: SystemCapability.Utils.Lang

W
wusongqing 已提交
1928 1929
**Parameters**

W
wusongqing 已提交
1930 1931 1932
| Name| Type           | Mandatory| Description          |
| ------ | --------------- | ---- | -------------- |
| evt    | [Event](#event) | Yes  | Event class for the callback to invoke.|
W
wusongqing 已提交
1933 1934 1935

**Return value**

W
wusongqing 已提交
1936 1937
| Type                                 | Description                           |
| ------------------------------------- | ------------------------------- |
W
wusongqing 已提交
1938 1939 1940 1941
| void&nbsp;\|&nbsp;Promise&lt;void&gt; | Returns no value or returns a **Promise**.|

**Example**

G
Gloria 已提交
1942
```js
1943
const workerInstance = new worker.Worker("workers/worker.ts");
W
wusongqing 已提交
1944 1945 1946 1947 1948 1949 1950 1951
workerInstance.addEventListener("alert", (e)=>{
    console.log("alert listener callback");
})
```


## ErrorEvent

G
Gloria 已提交
1952
Provides detailed information about the exception that occurs during worker execution. The **ErrorEvent** class inherits from [Event](#event).
W
wusongqing 已提交
1953 1954

**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1955

1956 1957 1958 1959 1960 1961 1962
| Name    | Type  | Readable| Writable| Description                |
| -------- | ------ | ---- | ---- | -------------------- |
| message  | string | Yes  | No  | Information about the exception.|
| filename | string | Yes  | No  | File where the exception is located.|
| lineno   | number | Yes  | No  | Serial number of the line where the exception is located.    |
| colno    | number | Yes  | No  | Serial number of the column where the exception is located.    |
| error    | Object | Yes  | No  | Type of the exception.          |
W
wusongqing 已提交
1963 1964


1965
## MessageEvent\<T\>
Z
zengyawen 已提交
1966

G
Gloria 已提交
1967
Holds the data transferred between worker threads.
Z
zengyawen 已提交
1968

W
wusongqing 已提交
1969
**System capability**: SystemCapability.Utils.Lang
W
wusongqing 已提交
1970

W
wusongqing 已提交
1971
| Name| Type| Readable| Writable| Description              |
1972 1973
| ---- | ---- | ---- | ---- | ------------------ |
| data | T    | Yes  | No  | Data transferred between threads.|
W
wusongqing 已提交
1974 1975


G
Gloria 已提交
1976 1977
## WorkerGlobalScope<sup>(deprecated)</sup>

G
Gloria 已提交
1978
Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget).
W
wusongqing 已提交
1979

1980 1981 1982
> **NOTE**<br>
> 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.

W
wusongqing 已提交
1983 1984
### Attributes

W
wusongqing 已提交
1985 1986
**System capability**: SystemCapability.Utils.Lang

1987
| Name| Type                                                        | Readable| Writable| Description                                 |
G
Gloria 已提交
1988
| ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- |
W
wusongqing 已提交
1989
| name | string                                                       | Yes  | No  | **Worker** instance specified when there is a new **Worker** instance.|
G
Gloria 已提交
1990
| self | [WorkerGlobalScope](#workerglobalscope)&nbsp;&amp;&nbsp;typeof&nbsp;globalThis | Yes  | No  | **WorkerGlobalScope**.              |
W
wusongqing 已提交
1991 1992


G
Gloria 已提交
1993 1994
### onerror<sup>(deprecated)</sup>

W
wusongqing 已提交
1995
onerror?: (ev: ErrorEvent) =&gt; void
Z
zengyawen 已提交
1996

G
Gloria 已提交
1997
Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread.
W
wusongqing 已提交
1998

1999
> **NOTE**<br>
G
Gloria 已提交
2000
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope<sup>9+</sup>.onerror<sup>9+</sup>](#onerror9-1).
2001

W
wusongqing 已提交
2002
**System capability**: SystemCapability.Utils.Lang
Z
zengyawen 已提交
2003

W
wusongqing 已提交
2004
**Parameters**
Z
zengyawen 已提交
2005

W
wusongqing 已提交
2006 2007
| Name| Type                     | Mandatory| Description      |
| ------ | ------------------------- | ---- | ---------- |
2008
| ev     | [ErrorEvent](#errorevent) | Yes  | Error data.|
Z
zengyawen 已提交
2009

W
wusongqing 已提交
2010
**Example**
W
wusongqing 已提交
2011

G
Gloria 已提交
2012
```js
2013
// Main thread
W
wusongqing 已提交
2014
import worker from '@ohos.worker';
2015
const workerInstance = new worker.Worker("workers/worker.ts")
W
wusongqing 已提交
2016
```
G
Gloria 已提交
2017
```js
2018
// worker.ts
W
wusongqing 已提交
2019 2020 2021
import worker from '@ohos.worker';
const parentPort = worker.parentPort
parentPort.onerror = function(e){
2022
    console.log("worker.ts onerror")
W
wusongqing 已提交
2023 2024
}
```
G
Gloria 已提交
2025

G
Gloria 已提交
2026

2027 2028 2029
## More Information

### Sequenceable Data Types
G
Gloria 已提交
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
| Type               | Remarks                                  | Supported|
| ------------------ | -------------------------------------- | -------- |
| All primitive types| The Symbol type is not included.                          | Yes      |
| Date               |                                        | Yes      |
| String             |                                        | Yes      |
| RegExp             |                                        | Yes      |
| Array              |                                        | Yes      |
| Map                |                                        | Yes      |
| Set                |                                        | Yes      |
| Object             | Only plain objects are supported. Objects with functions are not supported.| Yes      |
| ArrayBuffer        | The transfer capability is provided.                      | Yes      |
| TypedArray         |                                        | Yes      |
2042 2043

Exception: 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.
G
Gloria 已提交
2044 2045 2046
> **NOTE**<br>
> An FA project of API version 9 is used as an example.

2047
```js
2048
// Main thread
2049
import worker from '@ohos.worker';
2050 2051
const workerInstance = new worker.ThreadWorker("workers/worker.ts");
workerInstance.postMessage("message from main thread to worker");
2052 2053 2054 2055 2056 2057
workerInstance.onmessage = function(d) {
  // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method.
  let data = d.data;
}
```
```js
2058
// worker.ts
2059
import worker from '@ohos.worker';
2060
const workerPort = worker.workerPort;
2061
class MyModel {
2062
    name = "undefined"
2063
    Init() {
2064
        this.name = "MyModel"
2065 2066
    }
}
2067
workerPort.onmessage = function(d) {
2068
    console.log("worker.ts onmessage");
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
    let data = d.data;
    let func1 = function() {
        console.log("post message is function");
    }
    let obj1 = {
        "index": 2,
        "name1": "zhangshan",
        setName() {
            this.index = 3;
        }
    }
    let obj2 = new MyModel();
2081 2082 2083
    // workerPort.postMessage(func1); A serialization error occurs when passing func1.
    // workerPort.postMessage(obj1); A serialization error occurs when passing obj1.
    workerPort.postMessage(obj2);     // No serialization error occurs when passing obj2.
2084
}
2085
workerPort.onmessageerror = function(e) {
2086
    console.log("worker.ts onmessageerror");
2087
}
2088
workerPort.onerror = function(e) {
2089
    console.log("worker.ts onerror");
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
}
```

### Memory Model
The worker thread is implemented based on the actor model. In the worker interaction process, the JS main thread can create multiple worker threads, each of which are isolated and transfer data through sequentialization. They complete computing tasks and return the result to the main thread.

Each 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.

### Precautions
- Currently, a maximum of seven workers can co-exist.
G
Gloria 已提交
2100 2101
- In API version 8 and earlier versions, when the number of **Worker** instances exceeds the upper limit, the error "Too many workers, the number of workers exceeds the maximum." is thrown.
- Since API version 9, when the number of **Worker** instances exceeds the upper limit, the business error "Worker initialization failure, the number of workers exceeds the maximum" is thrown.
2102
- To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance.
G
Gloria 已提交
2103
- Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown.
2104
- Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them.
2105
- Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated).
2106
- When creating a **Worker** project, do not import any UI construction method (such as .ets file) to the worker thread file (for example, **worker.ts** used in this document). Otherwise, the worker module becomes invalid. To check whether any UI construction method has been imported, decompress the generated HAP file, find **worker.js** in the directory where the worker thread is created, and search for the keyword **View** globally. If the keyword exists, a UI construction method has been packaged in **worker.js**. If this is your case, change the directory level of **src** in the statement **import "xxx" from src** in the worker thread file.
2107

G
Gloria 已提交
2108
## Sample Code
G
Gloria 已提交
2109 2110
> **NOTE**<br>
> 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.
G
Gloria 已提交
2111
### FA Model
G
Gloria 已提交
2112

G
Gloria 已提交
2113
```js
2114
// Main thread (The following assumes that the workers directory and pages directory are at the same level.)
G
Gloria 已提交
2115
import worker from '@ohos.worker';
2116
// Create a Worker instance in the main thread.
G
Gloria 已提交
2117
const workerInstance = new worker.ThreadWorker("workers/worker.ts");
G
Gloria 已提交
2118

2119
// The main thread transfers information to the worker thread.
G
Gloria 已提交
2120
workerInstance.postMessage("123");
2121 2122

// The main thread receives information from the worker thread.
G
Gloria 已提交
2123
workerInstance.onmessage = function(e) {
2124
    // data carries the information sent by the worker thread.
G
Gloria 已提交
2125
    let data = e.data;
2126
    console.log("main thread onmessage");
2127 2128

    // Terminate the Worker instance.
G
Gloria 已提交
2129 2130
    workerInstance.terminate();
}
2131 2132

// Call onexit().
G
Gloria 已提交
2133
workerInstance.onexit = function() {
2134
    console.log("main thread terminate");
G
Gloria 已提交
2135 2136 2137
}
```
```js
G
Gloria 已提交
2138
// worker.ts
G
Gloria 已提交
2139
import worker from '@ohos.worker';
2140 2141

// Create an object in the worker thread for communicating with the main thread.
2142
const workerPort = worker.workerPort
G
Gloria 已提交
2143

2144
// The worker thread receives information from the main thread.
2145
workerPort.onmessage = function(e) {
2146
    // data carries the information sent by the main thread.
G
Gloria 已提交
2147
    let data = e.data;
G
Gloria 已提交
2148
    console.log("worker.ts onmessage");
2149 2150

    // The worker thread sends information to the main thread.
2151
    workerPort.postMessage("123")
G
Gloria 已提交
2152 2153
}

2154
// Trigger a callback when an error occurs in the worker thread.
2155
workerPort.onerror= function(e) {
G
Gloria 已提交
2156
    console.log("worker.ts onerror");
G
Gloria 已提交
2157 2158 2159 2160 2161 2162 2163
}
```
Configuration of the **build-profile.json5** file:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
2164
        "./src/main/ets/entryability/workers/worker.ts"
G
Gloria 已提交
2165 2166 2167 2168 2169 2170
      ]
    }
  }
```
### Stage Model
```js
2171
// Main thread (The following assumes that the workers directory and pages directory are at different levels.)
G
Gloria 已提交
2172
import worker from '@ohos.worker';
2173 2174

// Create a Worker instance in the main thread.
G
Gloria 已提交
2175
const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts");
2176 2177

// The main thread transfers information to the worker thread.
G
Gloria 已提交
2178
workerInstance.postMessage("123");
2179 2180

// The main thread receives information from the worker thread.
G
Gloria 已提交
2181
workerInstance.onmessage = function(e) {
2182
    // data carries the information sent by the worker thread.
G
Gloria 已提交
2183
    let data = e.data;
2184
    console.log("main thread onmessage");
2185 2186

    // Terminate the Worker instance.
G
Gloria 已提交
2187 2188
    workerInstance.terminate();
}
2189
// Call onexit().
G
Gloria 已提交
2190
workerInstance.onexit = function() {
2191
    console.log("main thread terminate");
G
Gloria 已提交
2192 2193 2194
}
```
```js
G
Gloria 已提交
2195
// worker.ts
G
Gloria 已提交
2196
import worker from '@ohos.worker';
2197 2198

// Create an object in the worker thread for communicating with the main thread.
2199
const workerPort = worker.workerPort
G
Gloria 已提交
2200

2201
// The worker thread receives information from the main thread.
2202
workerPort.onmessage = function(e) {
2203
    // data carries the information sent by the main thread.
G
Gloria 已提交
2204
    let data = e.data;
G
Gloria 已提交
2205
    console.log("worker.ts onmessage");
2206 2207

    // The worker thread sends information to the main thread.
2208
    workerPort.postMessage("123")
G
Gloria 已提交
2209 2210
}

2211
// Trigger a callback when an error occurs in the worker thread.
2212
workerPort.onerror= function(e) {
G
Gloria 已提交
2213
    console.log("worker.ts onerror");
G
Gloria 已提交
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
}
```
Configuration of the **build-profile.json5** file:
```json
  "buildOption": {
    "sourceOption": {
      "workers": [
        "./src/main/ets/pages/workers/worker.ts"
      ]
    }
  }
```
2226
<!--no_check-->