From 8e259595be954671417a2bcb3182cab4980f0f22 Mon Sep 17 00:00:00 2001 From: buzhuyu Date: Tue, 5 Sep 2023 10:59:14 +0800 Subject: [PATCH] =?UTF-8?q?g=E5=85=B1=E5=9F=BA=E7=A1=80=E7=B1=BB=E5=BA=93?= =?UTF-8?q?=E6=8C=87=E5=8D=97=E6=96=87=E6=A1=A3arkTs=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: buzhuyu --- .../arkts-utils/async-concurrency-overview.md | 20 +- .../cpu-intensive-task-development.md | 159 +++++----- .../io-intensive-task-development.md | 81 ++--- .../arkts-utils/linear-container.md | 2 +- .../multi-thread-concurrency-overview.md | 4 +- .../arkts-utils/nonlinear-container.md | 2 +- .../arkts-utils/single-io-development.md | 38 ++- .../arkts-utils/sync-task-development.md | 140 ++++----- .../arkts-utils/taskpool-vs-worker.md | 12 +- .../arkts-utils/xml-conversion.md | 9 +- .../arkts-utils/xml-generation.md | 11 +- .../arkts-utils/xml-parsing.md | 275 +++++++++-------- .../reference/apis/js-apis-taskpool.md | 4 +- .../reference/apis/js-apis-worker.md | 280 +++++++++--------- 14 files changed, 513 insertions(+), 524 deletions(-) diff --git a/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md b/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md index c0d45f2b7f..755e4526b6 100644 --- a/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md +++ b/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md @@ -16,7 +16,7 @@ Promise有三种状态:pending(进行中)、fulfilled(已完成)和rej 最基本的用法是通过构造函数实例化一个Promise对象,同时传入一个带有两个参数的函数,通常称为executor函数。executor函数接收两个参数:resolve和reject,分别表示异步操作成功和失败时的回调函数。例如,以下代码创建了一个Promise对象并模拟了一个异步操作: -```js +```ts const promise: Promise = new Promise((resolve: Function, reject: Function) => { setTimeout(() => { const randomNumber: number = Math.random(); @@ -26,7 +26,7 @@ setTimeout(() => { reject(new Error('Random number is too small')); } }, 1000); -} +}) ``` 上述代码中,setTimeout函数模拟了一个异步操作,并在1秒钟后随机生成一个数字。如果随机数大于0.5,则执行resolve回调函数并将随机数作为参数传递;否则执行reject回调函数并传递一个错误对象作为参数。 @@ -34,11 +34,13 @@ setTimeout(() => { Promise对象创建后,可以使用then方法和catch方法指定fulfilled状态和rejected状态的回调函数。then方法可接受两个参数,一个处理fulfilled状态的函数,另一个处理rejected状态的函数。只传一个参数则表示状态改变就执行,不区分状态结果。使用catch方法注册一个回调函数,用于处理“失败”的结果,即捕获Promise的状态改变为rejected状态或操作失败抛出的异常。例如: -```js -promise.then(result => { - console.info(`Random number is ${result}`); -}).catch(error => { - console.error(error.message); +```ts +import { BusinessError } from '@ohos.base'; + +promise.then((result: number) => { + console.info(`Random number is ${result}`); +}).catch((error: BusinessError) => { + console.error(error.message); }); ``` @@ -54,7 +56,7 @@ async函数是一个返回Promise对象的函数,用于表示一个异步操 下面是一个使用async/await的例子,其中模拟了一个异步操作,该操作会在3秒钟后返回一个字符串。 -```js +```ts async function myAsyncFunction(): Promise { const result: string = await new Promise((resolve: Function) => { setTimeout(() => { @@ -72,7 +74,7 @@ myAsyncFunction(); 需要注意的是,由于要等待异步操作完成,因此需要将整个操作包在async函数中。除了在async函数中使用await外,还可以使用try/catch块来捕获异步操作中的异常。 -```js +```ts async function myAsyncFunction(): Promise { try { const result: string = await new Promise((resolve: Function) => { diff --git a/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md b/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md index f2f4b93b64..be192804f7 100644 --- a/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md +++ b/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md @@ -19,7 +19,6 @@ CPU密集型任务是指需要占用系统资源处理大量计算能力的任 3. 结果数组汇总处理。 - ```ts import taskpool from '@ohos.taskpool'; @@ -58,8 +57,8 @@ struct Index { .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { - let data: ArrayBuffer; - histogramStatistic(data); + let buffer: ArrayBuffer = new ArrayBuffer(24); + histogramStatistic(buffer); }) } .width('100%') @@ -80,107 +79,105 @@ struct Index { 2. 在主线程中通过调用ThreadWorker的[constructor()](../reference/apis/js-apis-worker.md#constructor9)方法创建Worker对象,当前线程为宿主线程。 - ```js - import worker from '@ohos.worker'; + ```ts + import worker from '@ohos.worker'; - const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); - ``` + const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + ``` 3. 在宿主线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9)方法接收Worker线程发送过来的消息,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9)方法向Worker线程发送消息。 例如向Worker线程发送训练和预测的消息,同时接收Worker线程发送回来的消息。 - - ```js - // 接收Worker子线程的结果 - workerInstance.onmessage = function(e) { + ```ts + import worker from '@ohos.worker'; + + const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + + // 接收Worker子线程的结果 + workerInstance.onmessage = (() => { console.info('MyWorker.ts onmessage'); // 在Worker线程中进行耗时操作 - } - - workerInstance.onerror = function (d) { + }) + + workerInstance.onerror = (() => { // 接收Worker子线程的错误信息 - } + }) + + // 向Worker子线程发送训练消息 + workerInstance.postMessage({ 'type': 0 }); + // 向Worker子线程发送预测消息 + workerInstance.postMessage({ 'type': 1, 'value': [90, 5] }); + ``` - // 向Worker子线程发送训练消息 - workerInstance.postMessage({ 'type': 0 }); - // 向Worker子线程发送预测消息 - workerInstance.postMessage({ 'type': 1, 'value': [90, 5] }); - ``` 4. 在MyWorker.ts文件中绑定Worker对象,当前线程为Worker线程。 - ```js + ```ts import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; let workerPort: ThreadWorkerGlobalScope = worker.workerPort; ``` 5. 在Worker线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9-1)方法接收宿主线程发送的消息内容,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9-2)方法向宿主线程发送消息。 - 例如在Worker线程中定义预测模型及其训练过程,同时与主线程进行信息交互。 - - - ```js - import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; - - let workerPort: ThreadWorkerGlobalScope = worker.workerPort; - - // 定义训练模型及结果 - let result; - - // 定义预测函数 - function predict(x) { + 例如在Worker线程中定义预测模型及其训练过程,同时与主线程进行信息交互。 + + ```ts + import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; + // 定义训练模型及结果 + let result: Array; + // 定义预测函数 + function predict(x: number): number { return result[x]; - } - - // 定义优化器训练过程 - function optimize() { - result = {}; - } - - // Worker线程的onmessage逻辑 - workerPort.onmessage = (e: MessageEvents): void => { + } + // 定义优化器训练过程 + function optimize(): void { + result = []; + } + // Worker线程的onmessage逻辑 + workerPort.onmessage = (e: MessageEvents): void => { // 根据传输的数据的type选择进行操作 - switch (e.data.type) { - case 0: - // 进行训练 - optimize(); - // 训练之后发送主线程训练成功的消息 - workerPort.postMessage({ type: 'message', value: 'train success.' }); - break; - case 1: - // 执行预测 - const output = predict(e.data.value); - // 发送主线程预测的结果 - workerPort.postMessage({ type: 'predict', value: output }); - break; - default: - workerPort.postMessage({ type: 'message', value: 'send message is invalid' }); - break; + switch (e.data.type as number) { + case 0: + // 进行训练 + optimize(); + // 训练之后发送主线程训练成功的消息 + workerPort.postMessage({ type: 'message', value: 'train success.' }); + break; + case 1: + // 执行预测 + const output: number = predict(e.data.value as number); + // 发送主线程预测的结果 + workerPort.postMessage({ type: 'predict', value: output }); + break; + default: + workerPort.postMessage({ type: 'message', value: 'send message is invalid' }); + break; } - } - ``` + } + ``` 6. 在Worker线程中完成任务之后,执行Worker线程销毁操作。销毁线程的方式主要有两种:根据需要可以在宿主线程中对Worker线程进行销毁;也可以在Worker线程中主动销毁Worker线程。 - 在宿主线程中通过调用[onexit()](../reference/apis/js-apis-worker.md#onexit9)方法定义Worker线程销毁后的处理逻辑。 + 在宿主线程中通过调用[onexit()](../reference/apis/js-apis-worker.md#onexit9)方法定义Worker线程销毁后的处理逻辑。 - ```js - // Worker线程销毁后,执行onexit回调方法 - workerInstance.onexit = function() { + ```ts + // Worker线程销毁后,执行onexit回调方法 + workerInstance.onexit = (): void => { console.info("main thread terminate"); - } - ``` - - 方式一:在宿主线程中通过调用[terminate()](../reference/apis/js-apis-worker.md#terminate9)方法销毁Worker线程,并终止Worker接收消息。 - - ```js - // 销毁Worker线程 - workerInstance.terminate(); - ``` - - 方式二:在Worker线程中通过调用[close()](../reference/apis/js-apis-worker.md#close9)方法主动销毁Worker线程,并终止Worker接收消息。 - - ```js - // 销毁线程 - workerPort.close(); - ``` + } + ``` + + 方式一:在宿主线程中通过调用[terminate()](../reference/apis/js-apis-worker.md#terminate9)方法销毁Worker线程,并终止Worker接收息。 + + ```ts + // 销毁Worker线程 + workerInstance.terminate(); + ``` + + 方式二:在Worker线程中通过调用[close()](../reference/apis/js-apis-worker.md#close9)方法主动销毁Worker线程,并终止Worker接收消息。 + + ```ts + // 销毁线程 + workerPort.close(); + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md b/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md index 1a29cc3e00..10f0a6ef03 100644 --- a/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md +++ b/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md @@ -8,46 +8,49 @@ I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/ 1. 定义并发函数,内部密集调用I/O能力。 - - ```ts - import fs from '@ohos.file.fs'; - import { BusinessError } from '@ohos.base'; - - // 定义并发函数,内部密集调用I/O能力 - // 写入文件的实现 - async function write(data: string, filePath: string): Promise { - let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); - await fs.write(file.fd, data); - fs.close(file); - } - - @Concurrent - async function concurrentTest(fileList: string[]): Promise { - // 循环写文件操作 - for (let i: number = 0; i < fileList.length; i++) { - write('Hello World!', fileList[i]).then(() => { - console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); - }).catch((err: BusinessError) => { - console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) - return false; - }) + ```ts + // a.ts + import fs from '@ohos.file.fs'; + + // 定义并发函数,内部密集调用I/O能力 + // 写入文件的实现 + export async function write(data: string, filePath: string): Promise { + let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); + await fs.write(file.fd, data); + fs.close(file); + } + ``` + + ```ts + import { write } from './a' + import { BusinessError } from '@ohos.base'; + + @Concurrent + async function concurrentTest(fileList: string[]): Promise { + // 循环写文件操作 + for (let i: number = 0; i < fileList.length; i++) { + write('Hello World!', fileList[i]).then(() => { + console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); + }).catch((err: BusinessError) => { + console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) + return false; + }) + } + return true; } - return true; - } - ``` + ``` 2. 使用TaskPool执行包含密集I/O的并发函数:通过调用[execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute)方法执行任务,并在回调中进行调度结果处理。示例中的filePath1和filePath2的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 - ```ts - import taskpool from '@ohos.taskpool'; - - let filePath1: string = ...; // 应用文件路径 - let filePath2: string = ...; - - // 使用TaskPool执行包含密集I/O的并发函数 - // 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力 - taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => { - // 调度结果处理 - console.info(`The result: ${ret}`); - }) - ``` + ```ts + import taskpool from '@ohos.taskpool'; + + let filePath1: string = "path1"; // 应用文件路径 + let filePath2: string = "path2"; + + // 使用TaskPool执行包含密集I/O的并发函数 + // 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力 + taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => { + // 调度结果处理 + }) + ``` diff --git a/zh-cn/application-dev/arkts-utils/linear-container.md b/zh-cn/application-dev/arkts-utils/linear-container.md index 088b6c7272..7491babe88 100644 --- a/zh-cn/application-dev/arkts-utils/linear-container.md +++ b/zh-cn/application-dev/arkts-utils/linear-container.md @@ -198,7 +198,7 @@ Stack进行增、删、改、查操作的常用API如下: 此处列举常用的线性容器ArrayList、Vector、Deque、Stack、List的使用示例,包括导入模块、增加元素、访问元素及修改等操作。示例代码如下所示: -```js +```ts // ArrayList import ArrayList from '@ohos.util.ArrayList'; // 导入ArrayList模块 diff --git a/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md b/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md index 31271ee693..5e33544e5d 100644 --- a/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md +++ b/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md @@ -27,7 +27,7 @@ Actor并发模型作为基于消息通信并发模型的典型代表,不需要 可转移对象(Transferable object)传输采用地址转移进行序列化,不需要内容拷贝,会将ArrayBuffer的所有权转移给接收该ArrayBuffer的线程,转移后该ArrayBuffer在发送它的线程中变为不可用,不允许再访问。 -```js +```ts // 定义可转移对象 let buffer: ArrayBuffer = new ArrayBuffer(100); ``` @@ -42,7 +42,7 @@ let buffer: ArrayBuffer = new ArrayBuffer(100); SharedArrayBuffer对象存储的数据在同时被修改时,需要通过原子操作保证其同步性,即下个操作开始之前务必需要等到上个操作已经结束。 -```js +```ts // 定义可共享对象,可以使用Atomics进行操作 let sharedBuffer: SharedArrayBuffer = new SharedArrayBuffer(1024); ``` diff --git a/zh-cn/application-dev/arkts-utils/nonlinear-container.md b/zh-cn/application-dev/arkts-utils/nonlinear-container.md index 0b35b767bf..098b1d79ae 100644 --- a/zh-cn/application-dev/arkts-utils/nonlinear-container.md +++ b/zh-cn/application-dev/arkts-utils/nonlinear-container.md @@ -212,7 +212,7 @@ PlainArray进行增、删、改、查操作的常用API如下: 此处列举常用的非线性容器HashMap、TreeMap、LightWeightMap、PlainArray的使用示例,包括导入模块、增加元素、访问元素及修改等操作,示例代码如下所示: -```js +```ts // HashMap import HashMap from '@ohos.util.HashMap'; // 导入HashMap模块 diff --git a/zh-cn/application-dev/arkts-utils/single-io-development.md b/zh-cn/application-dev/arkts-utils/single-io-development.md index 6b551373ea..533fd02d80 100644 --- a/zh-cn/application-dev/arkts-utils/single-io-development.md +++ b/zh-cn/application-dev/arkts-utils/single-io-development.md @@ -6,25 +6,23 @@ Promise和async/await提供异步并发能力,适用于单次I/O任务的场 1. 实现单次I/O任务逻辑。 - ```js - import fs from '@ohos.file.fs'; - import { BusinessError } from '@ohos.base'; - - async function write(data: string, filePath: string): Promise { - let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); - fs.write(file.fd, data).then((writeLen: number) => { - fs.close(file); - }).catch((err: BusinessError) => { - console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); - }) - } - ``` - + ```ts + import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; + async function write(data: string, filePath: string): Promise { + let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); + fs.write(file.fd, data).then((writeLen: number) => { + fs.close(file); + }).catch((err: BusinessError) => { + console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); + }) + } + ``` 2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 - ```js - let filePath: string = ...; // 应用文件路径 - write('Hello World!', filePath).then(() => { - console.info('Succeeded in writing data.'); - }) - ``` + ```ts + let filePath: string = "path"; // 应用文件路径 + write('Hello World!', filePath).then(() => { + console.info('Succeeded in writing data.'); + }) + ``` diff --git a/zh-cn/application-dev/arkts-utils/sync-task-development.md b/zh-cn/application-dev/arkts-utils/sync-task-development.md index 6fbb549708..72b28a4325 100644 --- a/zh-cn/application-dev/arkts-utils/sync-task-development.md +++ b/zh-cn/application-dev/arkts-utils/sync-task-development.md @@ -39,6 +39,7 @@ export default class Handle { } ``` + 业务使用TaskPool调用相关同步方法的代码。 @@ -52,8 +53,6 @@ import Handle from './Handle'; // 返回静态句柄 function func(num: number): boolean { // 调用静态类对象中实现的同步等待调用 Handle.syncSet(num); - // 或者调用单例对象中实现的同步等待调用 - Handle.getInstance().syncGet(); return true; } @@ -95,75 +94,76 @@ struct Index { 1. 在主线程中创建Worker对象,同时接收Worker线程发送回来的消息。 - ```js - import worker from '@ohos.worker'; - - @Entry - @Component - struct Index { - @State message: string = 'Hello World'; - - build() { - Row() { - Column() { - Text(this.message) - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(() => { - let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); - w.onmessage = function (d) { - // 接收Worker子线程的结果 - } - w.onerror = function (d) { - // 接收Worker子线程的错误信息 - } - // 向Worker子线程发送Set消息 - w.postMessage({'type': 0, 'data': 'data'}) - // 向Worker子线程发送Get消息 - w.postMessage({'type': 1}) - // 销毁线程 - w.terminate() - }) - } - .width('100%') - } - .height('100%') - } - } - ``` + ```ts + import worker from '@ohos.worker'; + + @Entry + @Component + struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + w.onmessage = () => { + // 接收Worker子线程的结果 + } + w.onerror = () => { + // 接收Worker子线程的错误信息 + } + // 向Worker子线程发送Set消息 + w.postMessage({'type': 0, 'data': 'data'}) + // 向Worker子线程发送Get消息 + w.postMessage({'type': 1}) + // 销毁线程 + w.terminate() + }) + } + .width('100%') + } + .height('100%') + } + } + ``` -2. 在Worker线程中绑定Worker对象,同时处理同步任务逻辑。 - ```js - // handle.ts代码 - export default class Handle { - syncGet() { - return; - } +2. 在Worker线程中绑定Worker对象,同时处理同步任务逻辑。 - syncSet(num: number) { - return; - } - } - - // Worker.ts代码 - import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; - import Handle from './handle.ts' // 返回句柄 - - var workerPort : ThreadWorkerGlobalScope = worker.workerPort; - - // 无法传输的句柄,所有操作依赖此句柄 - var handler = new Handle() - - // Worker线程的onmessage逻辑 - workerPort.onmessage = function(e : MessageEvents) { - switch (e.data.type) { - case 0: - handler.syncSet(e.data.data); - workerPort.postMessage('success set'); - case 1: - handler.syncGet(); - workerPort.postMessage('success get'); + ```ts + // handle.ts代码 + export default class Handle { + syncGet() { + return; + } + + syncSet(num: number) { + return; + } + } + + // Worker.ts代码 + import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; + import Handle from './handle.ts' // 返回句柄 + + var workerPort : ThreadWorkerGlobalScope = worker.workerPort; + + // 无法传输的句柄,所有操作依赖此句柄 + var handler = new Handle() + + // Worker线程的onmessage逻辑 + workerPort.onmessage = (e : MessageEvents): void => { + switch (e.data.type as number) { + case 0: + handler.syncSet(e.data.data); + workerPort.postMessage('success set'); + case 1: + handler.syncGet(); + workerPort.postMessage('success get'); } - } - ``` + } + ``` diff --git a/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md b/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md index a4f0cd4d8d..ece6fcee20 100644 --- a/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md +++ b/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md @@ -100,23 +100,21 @@ TaskPool支持开发者在主线程封装任务抛给任务队列,系统选择 当使用Worker模块具体功能时,均需先构造Worker实例对象,其构造函数与API版本相关。 -```js +```ts // API 9及之后版本使用: -const worker1: worker.ThreadWorker = new worker.ThreadWorker(scriptURL); +const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); // API 8及之前版本使用: -const worker1: worker.ThreadWorker = new worker.Worker(scriptURL); +const worker2: worker.Worker = new worker.Worker('entry/ets/workers/MyWorker.ts'); ``` 构造函数需要传入Worker的路径(scriptURL),Worker文件存放位置默认路径为Worker文件所在目录与pages目录属于同级。 **Stage模型** - 构造函数中的scriptURL示例如下: - -```js +```ts // 写法一 // Stage模型-目录同级(entry模块下,workers目录与pages目录同级) const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); @@ -149,7 +147,7 @@ const worker4: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.exampl 构造函数中的scriptURL示例如下: -```js +```ts // FA模型-目录同级(entry模块下,workers目录与pages目录同级) const worker1: worker.ThreadWorker = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); // FA模型-目录不同级(entry模块下,workers目录与pages目录的父目录同级) diff --git a/zh-cn/application-dev/arkts-utils/xml-conversion.md b/zh-cn/application-dev/arkts-utils/xml-conversion.md index 100d5112be..789ab6dad5 100644 --- a/zh-cn/application-dev/arkts-utils/xml-conversion.md +++ b/zh-cn/application-dev/arkts-utils/xml-conversion.md @@ -18,15 +18,15 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 1. 引入模块。 - ```js + ```ts import convertxml from '@ohos.convertxml'; ``` 2. 输入待转换的XML,设置转换选项。 - ```js + ```ts let xml: string = - '' + + '' + '' + ' Happy' + ' Work' + @@ -62,7 +62,7 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 3. 调用转换函数,打印结果。 - ```js + ```ts let conv: convertxml.ConvertXML = new convertxml.ConvertXML(); let result: object = conv.convertToJSObject(xml, options); let strRes: string = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出 @@ -71,7 +71,6 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 输出结果如下所示: - ```js strRes: {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note", diff --git a/zh-cn/application-dev/arkts-utils/xml-generation.md b/zh-cn/application-dev/arkts-utils/xml-generation.md index 60edf5c6d3..afe0deca6a 100644 --- a/zh-cn/application-dev/arkts-utils/xml-generation.md +++ b/zh-cn/application-dev/arkts-utils/xml-generation.md @@ -24,14 +24,14 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) 1. 引入模块。 - ```js + ```ts import xml from '@ohos.xml'; import util from '@ohos.util'; ``` 2. 创建缓冲区,构造XmlSerializer对象(可以基于Arraybuffer构造XmlSerializer对象, 也可以基于DataView构造XmlSerializer对象)。 - ```js + ```ts // 1.基于Arraybuffer构造XmlSerializer对象 let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 let thatSer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象 @@ -44,7 +44,7 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) 3. 调用XML元素生成函数。 - ```js + ```ts thatSer.setDeclaration(); // 写入xml的声明 thatSer.startElement('bookstore'); // 写入元素开始标记 thatSer.startElement('book'); // 嵌套元素开始标记 @@ -65,7 +65,7 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) 4. 使用Uint8Array操作Arraybuffer,调用TextDecoder对Uint8Array解码后输出。 - ```js + ```ts let view: Uint8Array = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据 let textDecoder: util.TextDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类 let res: string = textDecoder.decodeWithStream(view); // 对view解码 @@ -74,7 +74,6 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) 输出结果如下: - - ```js + ``` \r\n \r\n Everyday\r\n Giada\r\n 2005\r\n \r\n ``` diff --git a/zh-cn/application-dev/arkts-utils/xml-parsing.md b/zh-cn/application-dev/arkts-utils/xml-parsing.md index 5df577246c..bff61b63f8 100644 --- a/zh-cn/application-dev/arkts-utils/xml-parsing.md +++ b/zh-cn/application-dev/arkts-utils/xml-parsing.md @@ -29,111 +29,109 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A 1. 引入模块。 - ```js - import xml from '@ohos.xml'; - import util from '@ohos.util'; // 需要使用util模块函数对文件编码 - ``` + ```ts + import xml from '@ohos.xml'; + import util from '@ohos.util'; // 需要使用util模块函数对文件编码 + ``` 2. 对XML文件编码后调用XmlPullParser。 可以基于ArrayBuffer构造XmlPullParser对象, 也可以基于DataView构造XmlPullParser对象。 - - ```js - let strXml: string = - '' + - '' + - 'Play' + - 'Work' + - ''; - let textEncoder: util.TextEncoder = new util.TextEncoder(); - let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - // 1.基于ArrayBuffer构造XmlPullParser对象 - let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); - - // 2.基于DataView构造XmlPullParser对象 - let dataView: DataView = new DataView(arrBuffer.buffer); - let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8'); - ``` + ```ts + let strXml: string = + '' + + '' + + 'Play' + + 'Work' + + ''; + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + // 1.基于ArrayBuffer构造XmlPullParser对象 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + + // 2.基于DataView构造XmlPullParser对象 + let dataView: DataView = new DataView(arrBuffer.buffer); + let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8'); + ``` 3. 自定义回调函数,本例直接打印出标签及标签值。 - ```js - let str: string = ''; - function func(name: string, value: string): boolean { - str = name + value; - console.info(str); - return true; //true:继续解析 false:停止解析 - } - ``` + ```ts + let str: string = ''; + function func(name: string, value: string): boolean { + str = name + value; + console.info(str); + return true; //true:继续解析 false:停止解析 + } + ``` 4. 设置解析选项,调用parse函数。 - ```js - let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; - that.parse(options); - ``` + ```ts + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; + that.parse(options); + ``` - 输出结果如下所示: + 输出结果如下所示: + + ``` + note + title + Play + title + lens + Work + lens + note + ``` - ```js - note - title - Play - title - lens - Work - lens - note - ``` ## 解析XML属性和属性值 1. 引入模块。 - ```js - import xml from '@ohos.xml'; - import util from '@ohos.util'; // 需要使用util模块函数对文件编码 - ``` + ```ts + import xml from '@ohos.xml'; + import util from '@ohos.util'; // 需要使用util模块函数对文件编码 + ``` 2. 对XML文件编码后调用XmlPullParser。 - ```js - let strXml: string = - '' + - '' + - ' Play' + - ' Happy' + - ' Work' + - ''; - let textEncoder: util.TextEncoder = new util.TextEncoder(); - let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); - ``` + ```ts + let strXml: string = + '' + + '' + + ' Play' + + ' Happy' + + ' Work' + + ''; + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + ``` 3. 自定义回调函数,本例直接打印出属性及属性值。 - ```js - let str: string = ''; - function func(name: string, value: string): boolean { - str += name + ' ' + value + ' '; - return true; // true:继续解析 false:停止解析 - } - ``` + ```ts + let str: string = ''; + function func(name: string, value: string): boolean { + str += name + ' ' + value + ' '; + return true; // true:继续解析 false:停止解析 + } + ``` 4. 设置解析选项,调用parse函数。 - ```js - let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; - that.parse(options); - console.info(str); // 一次打印出所有的属性及其值 - ``` + ```ts + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; + that.parse(options); + console.info(str); // 一次打印出所有的属性及其值 + ``` 输出结果如下所示: - - - ```js + ``` importance high logged true // note节点的属性及属性值 ``` @@ -142,54 +140,55 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A 1. 引入模块。 - ```js - import xml from '@ohos.xml'; - import util from '@ohos.util'; // 需要使用util模块函数对文件编码 - ``` + ```ts + import xml from '@ohos.xml'; + import util from '@ohos.util'; // 需要使用util模块函数对文件编码 + ``` 2. 对XML文件编码后调用XmlPullParser。 - ```js - let strXml: string = - '' + - '' + - 'Play' + - ''; - let textEncoder: util.TextEncoder = new util.TextEncoder(); - let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); - ``` + ```ts + let strXml: string = + '' + + '' + + 'Play' + + ''; + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + ``` 3. 自定义回调函数,本例直接打印元素事件类型及元素深度。 - ```js - let str: string = ''; - function func(name: string, value: xml.ParseInfo): boolean { - str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度 - console.info(str) - return true; //true:继续解析 false:停止解析 - } - ``` + ```ts + let str: string = ''; + function func(name: xml.EventType, value: xml.ParseInfo): boolean { + str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度 + console.info(str) + return true; //true:继续解析 false:停止解析 + } + ``` 4. 设置解析选项,调用parse函数。 - ```js - let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; - that.parse(options); - ``` + ```ts + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; + that.parse(options); + ``` 输出结果如下所示: + ``` + 0 0 // 0: 对应事件类型 START_DOCUMENT值为0 0:起始深度为0 + 2 1 // 2: 对应事件类型START_TAG值为2 1:深度为1 + 2 2 // 2:对应事件类型START_TAG值为2 2:深度为2 + 4 2 // 4:Play对应事件类型TEXT值为4 2:深度为2 + 3 2 // 3:对应事件类型END_TAG值为3 2:深度为2 + 3 1 // 3:对应事件类型END_TAG值为3 1:深度为1(与) + 1 0 // 1:对应事件类型END_DOCUMENT值为1 0:深度为0 + ``` + - ```js - 0 0 // 0: 对应事件类型START_DOCUMENT值为0 0:起始深度为0 - 2 1 // 2: 对应事件类型START_TAG值为2 1:深度为1 - 2 2 // 2:对应事件类型START_TAG值为2 2:深度为2 - 4 2 // 4:Play对应事件类型TEXT值为4 2:深度为2 - 3 2 // 3:对应事件类型END_TAG值为3 2:深度为2 - 3 1 // 3:对应事件类型END_TAG值为3 1:深度为1(与) - 1 0 // 1:对应事件类型END_DOCUMENT值为1 0:深度为0 - ``` ## 场景示例 @@ -197,7 +196,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A 此处以调用所有解析选项为例,提供解析XML标签、属性和事件类型的开发示例。 -```js +```ts import xml from '@ohos.xml'; import util from '@ohos.util'; @@ -218,13 +217,13 @@ function tagFunc(name: string, value: string): boolean { return true; } -function attFunc(name: string, value: string): boolean { +function attFunc(name: xml.EventType, value: string): boolean { str = name + ' ' + value; console.info('attri-' + str); return true; } -function tokenFunc(name: string, value: xml.ParseInfo): boolean { +function tokenFunc(name: xml.EventType, value: xml.ParseInfo): boolean { str = name + ' ' + value.getDepth(); console.info('token-' + str); return true; @@ -238,33 +237,31 @@ let options: xml.ParseOptions = { tokenValueCallbackFunction: tokenFunc }; that.parse(options); - ``` 输出结果如下所示: - -```js -tag- -token-0 0 -tag-book -attri-category COOKING -token-2 1 -tag-title -attri-lang en -token-2 2 -tag-Everyday -token-4 2 -tag-title -token-3 2 -tag-author -token-2 2 -tag-Giada -token-4 2 -tag-author -token-3 2 -tag-book -token-3 1 -tag- -token-1 0 -``` + ``` + tag- + token-0 0 + tag-book + attri-category COOKING + token-2 1 + tag-title + attri-lang en + token-2 2 + tag-Everyday + token-4 2 + tag-title + token-3 2 + tag-author + token-2 2 + tag-Giada + token-4 2 + tag-author + token-3 2 + tag-book + token-3 1 + tag- + token-1 0 + ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md index ece8779b4b..825bfee929 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md +++ b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md @@ -688,7 +688,7 @@ taskpoolExecute(); ```ts // b.ets -export let c: number = 2000; +export let c: string = "hello"; ``` ```ts // 引用import变量 @@ -696,7 +696,7 @@ export let c: number = 2000; import { c } from "./b"; @Concurrent -function printArgs(a: number): number { +function printArgs(a: string): string { console.log(a); console.log(c); return a; diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index bdcaa44e32..8c47b558ad 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -11,7 +11,7 @@ Worker的上下文对象和主线程的上下文对象是不同的,Worker线 ## 导入模块 -```js +```ts import worker from '@ohos.worker'; ``` @@ -77,7 +77,7 @@ ThreadWorker构造函数。 **示例:** -```js +```ts import worker from '@ohos.worker'; // worker线程创建 @@ -184,10 +184,10 @@ postMessage(message: Object, transfer: ArrayBuffer[]): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); -var buffer = new ArrayBuffer(8); +let buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -217,12 +217,12 @@ postMessage(message: Object, options?: PostMessageOptions): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); -var buffer = new ArrayBuffer(8); +let buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -252,7 +252,7 @@ on(type: string, listener: WorkerEventListener): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.on("alert", (e)=>{ console.log("alert listener callback"); @@ -286,7 +286,7 @@ once(type: string, listener: WorkerEventListener): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); @@ -320,7 +320,7 @@ off(type: string, listener?: WorkerEventListener): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); //使用on接口、once接口或addEventListener接口创建“alert”事件,使用off接口删除事件。 workerInstance.off("alert"); @@ -345,7 +345,7 @@ terminate(): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.terminate(); ``` @@ -376,10 +376,10 @@ Worker对象的onexit属性表示Worker销毁时被调用的事件处理程序 **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); -workerInstance.onexit = function(e) { - console.log("onexit"); +workerInstance.onexit = () => { + console.log("onexit"); } //onexit被执行两种方式: @@ -416,9 +416,9 @@ Worker对象的onerror属性表示Worker在执行过程中发生异常被调用 **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); -workerInstance.onerror = function(e) { +workerInstance.onerror = () => { console.log("onerror"); } ``` @@ -449,12 +449,14 @@ Worker对象的onmessage属性表示宿主线程接收到来自其创建的Worke **示例:** -```js +```ts +import worker, { MessageEvents } from '@ohos.worker'; + const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); -workerInstance.onmessage = function(e) { - // e : MessageEvents, 用法如下: - // let data = e.data; - console.log("onmessage"); +workerInstance.onmessage = (e: MessageEvents): void => { + // e : MessageEvents, 用法如下: + // let data = e.data; + console.log("onmessage"); } ``` @@ -484,9 +486,9 @@ Worker对象的onmessageerror属性表示当Worker对象接收到一条无法被 **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); -workerInstance.onmessageerror= function(e) { +workerInstance.onmessageerror= () => { console.log("onmessageerror"); } ``` @@ -517,7 +519,7 @@ addEventListener(type: string, listener: WorkerEventListener): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -550,7 +552,7 @@ removeEventListener(type: string, callback?: WorkerEventListener): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -589,7 +591,7 @@ dispatchEvent(event: Event): boolean **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); //timeStamp暂未支持。 @@ -597,7 +599,7 @@ workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); //timeStamp暂未 分发事件(dispatchEvent)可与监听接口(on、once、addEventListener)搭配使用,示例如下: -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); //用法一: @@ -630,7 +632,7 @@ workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.addEventListener("message", (e)=>{ console.log("message listener callback"); }) -workerInstance.onmessage = function(e) { +workerInstance.onmessage = (e: MessageEvents): void => { console.log("onmessage : message listener callback"); } //调用dispatchEvent分发“message”事件,addEventListener和onmessage中定义的方法都会被执行。 @@ -656,7 +658,7 @@ removeAllListener(): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -692,7 +694,7 @@ addEventListener(type: string, listener: WorkerEventListener): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -725,7 +727,7 @@ removeEventListener(type: string, callback?: WorkerEventListener): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -764,7 +766,7 @@ dispatchEvent(event: Event): boolean **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); //timeStamp暂未支持。 @@ -772,7 +774,7 @@ workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); //timeStamp暂未 分发事件(dispatchEvent)可与监听接口(on、once、addEventListener)搭配使用,示例如下: -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); //用法一: @@ -805,7 +807,7 @@ workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.addEventListener("message", (e)=>{ console.log("message listener callback"); }) -workerInstance.onmessage = function(e) { +workerInstance.onmessage = (e: MessageEvents): void => { console.log("onmessage : message listener callback"); } //调用dispatchEvent分发“message”事件,addEventListener和onmessage中定义的方法都会被执行。 @@ -831,7 +833,7 @@ removeAllListener(): void **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -870,24 +872,22 @@ Worker线程通过转移对象所有权的方式向宿主线程发送消息。 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); -workerInstance.onmessage = function(e) { - // let data = e.data; +workerInstance.onmessage = (e: MessageEvents): void => { console.log("receive data from worker.ts"); } ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; -workerPort.onmessage = function(e){ - // let data = e.data; - var buffer = new ArrayBuffer(8); +workerPort.onmessage = (e: MessageEvents): void => { + let buffer = new ArrayBuffer(8); workerPort.postMessage(buffer, [buffer]); } ``` @@ -918,23 +918,21 @@ Worker线程通过转移对象所有权或者拷贝数据的方式向宿主线 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); -workerInstance.onmessage = function(e) { - // let data = e.data; +workerInstance.onmessage = (e: MessageEvents): void => { console.log("receive data from worker.ts"); } ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; -workerPort.onmessage = function(e){ - // let data = e.data; +workerPort.onmessage = (e: MessageEvents): void => { workerPort.postMessage("receive data from main thread"); } ``` @@ -958,17 +956,17 @@ close(): void **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; -workerPort.onmessage = function(e) { +workerPort.onmessage = (e: MessageEvents): void => { workerPort.close() } ``` @@ -1000,18 +998,18 @@ ThreadWorkerGlobalScope的onmessage属性表示Worker线程收到来自其宿主 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); workerInstance.postMessage("hello world"); ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; -workerPort.onmessage = function(e) { +workerPort.onmessage = (e: MessageEvents): void => { console.log("receive main thread message"); } ``` @@ -1043,17 +1041,17 @@ ThreadWorkerGlobalScope的onmessageerror属性表示当Worker对象接收到一 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; -workerPort.onmessageerror = function(e) { +workerPort.onmessageerror = () => { console.log("worker.ts onmessageerror") } ``` @@ -1090,9 +1088,9 @@ workerPort.onmessageerror = function(e) { **示例:** -```js +```ts const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); -workerInstance.addEventListener("alert", (e)=>{ +workerInstance.addEventListener("alert", ()=>{ console.log("alert listener callback"); }) ``` @@ -1128,17 +1126,17 @@ GlobalScope的onerror属性表示Worker在执行过程中发生异常被调用 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts") ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort -workerPort.onerror = function(e){ +workerPort.onerror = () => { console.log("worker.ts onerror") } ``` @@ -1187,7 +1185,7 @@ Worker构造函数。 **示例:** -```js +```ts import worker from '@ohos.worker'; // worker线程创建 @@ -1273,10 +1271,10 @@ postMessage(message: Object, transfer: ArrayBuffer[]): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -var buffer = new ArrayBuffer(8); +let buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -1300,12 +1298,12 @@ postMessage(message: Object, options?: PostMessageOptions): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); -var buffer = new ArrayBuffer(8); +let buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -1330,9 +1328,9 @@ on(type: string, listener: EventListener): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -workerInstance.on("alert", (e)=>{ +workerInstance.on("alert", ()=>{ console.log("alert listener callback"); }) ``` @@ -1358,7 +1356,7 @@ once(type: string, listener: EventListener): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); @@ -1386,7 +1384,7 @@ off(type: string, listener?: EventListener): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); //使用on接口、once接口或addEventListener接口创建“alert”事件,使用off接口删除事件。 workerInstance.off("alert"); @@ -1406,7 +1404,7 @@ terminate(): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.terminate(); ``` @@ -1431,9 +1429,9 @@ Worker对象的onexit属性表示Worker销毁时被调用的事件处理程序 **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -workerInstance.onexit = function(e) { +workerInstance.onexit = () => { console.log("onexit"); } @@ -1465,9 +1463,9 @@ Worker对象的onerror属性表示Worker在执行过程中发生异常被调用 **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -workerInstance.onerror = function(e) { +workerInstance.onerror = function() { console.log("onerror"); } ``` @@ -1492,11 +1490,9 @@ Worker对象的onmessage属性表示宿主线程接收到来自其创建的Worke **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -workerInstance.onmessage = function(e) { - // e : MessageEvent, 用法如下: - // let data = e.data; +workerInstance.onmessage = (e: MessageEvents): void => { console.log("onmessage"); } ``` @@ -1521,9 +1517,9 @@ Worker对象的onmessageerror属性表示当Worker对象接收到一条无法被 **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -workerInstance.onmessageerror= function(e) { +workerInstance.onmessageerror= () => { console.log("onmessageerror"); } ``` @@ -1553,9 +1549,9 @@ addEventListener(type: string, listener: EventListener): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -workerInstance.addEventListener("alert", (e)=>{ +workerInstance.addEventListener("alert", ()=>{ console.log("alert listener callback"); }) ``` @@ -1581,9 +1577,9 @@ removeEventListener(type: string, callback?: EventListener): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -workerInstance.addEventListener("alert", (e)=>{ +workerInstance.addEventListener("alert", ()=>{ console.log("alert listener callback"); }) workerInstance.removeEventListener("alert"); @@ -1615,7 +1611,7 @@ dispatchEvent(event: Event): boolean **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); //timeStamp暂未支持。 @@ -1623,7 +1619,7 @@ workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); //timeStamp暂未 分发事件(dispatchEvent)可与监听接口(on、once、addEventListener)搭配使用,示例如下: -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); //用法一: @@ -1675,7 +1671,7 @@ removeAllListener(): void **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -1729,21 +1725,21 @@ Worker线程通过转移对象所有权的方式向宿主线程发送消息。 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); -workerInstance.onmessage = function(e) { +workerInstance.onmessage = (e: MessageEvents): void => { // let data = e.data; console.log("receive data from worker.ts"); } ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const workerPort = worker.workerPort; -workerPort.onmessage = function(e){ +workerPort.onmessage = (e: MessageEvents): void => { // let data = e.data; let buffer = new ArrayBuffer(5) workerPort.postMessage(buffer, [buffer]); @@ -1770,21 +1766,21 @@ Worker线程通过转移对象所有权或者拷贝数据的方式向宿主线 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); -workerInstance.onmessage = function(e) { +workerInstance.onmessage = (e: MessageEvents): void => { // let data = e.data; console.log("receive data from worker.ts"); } ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; -parentPort.onmessage = function(e){ +parentPort.onmessage = (e: MessageEvents): void => { // let data = e.data; parentPort.postMessage("receive data from main thread"); } @@ -1803,16 +1799,16 @@ close(): void **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.Worker("workers/worker.ts"); ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; -parentPort.onmessage = function(e) { +parentPort.onmessage = (e: MessageEvents): void => { parentPort.close() } ``` @@ -1838,17 +1834,17 @@ DedicatedWorkerGlobalScope的onmessage属性表示Worker线程收到来自其宿 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.Worker("workers/worker.ts"); workerInstance.postMessage("hello world"); ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; -parentPort.onmessage = function(e) { +parentPort.onmessage = (e: MessageEvents): void => { console.log("receive main thread message"); } ``` @@ -1874,16 +1870,16 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当Worker对象接收到 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.Worker("workers/worker.ts"); ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort; -parentPort.onmessageerror = function(e) { +parentPort.onmessageerror = () => { console.log("worker.ts onmessageerror") } ``` @@ -1937,9 +1933,9 @@ parentPort.onmessageerror = function(e) { **示例:** -```js +```ts const workerInstance = new worker.Worker("workers/worker.ts"); -workerInstance.addEventListener("alert", (e)=>{ +workerInstance.addEventListener("alert", ()=>{ console.log("alert listener callback"); }) ``` @@ -2007,16 +2003,16 @@ WorkerGlobalScope的onerror属性表示Worker在执行过程中发生异常被 **示例:** -```js +```ts // main thread import worker from '@ohos.worker'; const workerInstance = new worker.Worker("workers/worker.ts") ``` -```js +```ts // worker.ts import worker from '@ohos.worker'; const parentPort = worker.parentPort -parentPort.onerror = function(e){ +parentPort.onerror = () => { console.log("worker.ts onerror") } ``` @@ -2032,19 +2028,19 @@ parentPort.onerror = function(e){ > **说明:**
> 以API version 9的FA工程为例。 -```js +```ts // main thread -import worker from '@ohos.worker'; +import worker, { MessageEvents } from '@ohos.worker'; const workerInstance = new worker.ThreadWorker("workers/worker.ts"); workerInstance.postMessage("message from main thread to worker"); -workerInstance.onmessage = function(d) { +workerInstance.onmessage = (d: MessageEvents): void => { // 当worker线程传递obj2时,data即为obj2。data没有Init、SetName的方法 - let data = d.data; + let data: string = d.data; } ``` -```js +```ts // worker.ts -import worker from '@ohos.worker'; +import worker, { MessageEvents } from '@ohos.worker'; const workerPort = worker.workerPort; class MyModel { name = "undefined" @@ -2052,10 +2048,10 @@ class MyModel { this.name = "MyModel" } } -workerPort.onmessage = function(d) { +workerPort.onmessage = (d: MessageEvents): void => { console.log("worker.ts onmessage"); - let data = d.data; - let func1 = function() { + let data: string = d.data; + let func1 = () => { console.log("post message is function"); } let obj1 = { @@ -2070,16 +2066,16 @@ workerPort.onmessage = function(d) { // workerPort.postMessage(obj1); 传递obj1发生序列化错误 workerPort.postMessage(obj2); // 传递obj2不会发生序列化错误 } -workerPort.onmessageerror = function(e) { +workerPort.onmessageerror = () => { console.log("worker.ts onmessageerror"); } -workerPort.onerror = function(e) { +workerPort.onerror = () => { console.log("worker.ts onerror"); } ``` ### 内存模型 -Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程可以创建多个Worker子线程,各个Worker线程间相互隔离,并通过序列化传递对象,等到Worker线程完成计算任务,再把结果返回给主线程。 +Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程可以创建多个Worker子线程,各个Worker线程间相互隔离,并通过序列化传递对象,等到Worker线程完成计算任务,再把结果返回给主线程。 Actor并发模型的交互原理:各个Actor并发地处理主线程任务,每个Actor内部都有一个消息队列及单线程执行模块,消息队列负责接收主线程及其他Actor的请求,单线程执行模块则负责串行地处理请求、向其他Actor发送请求以及创建新的Actor。由于Actor采用的是异步方式,各个Actor之间相互隔离没有数据竞争,因此Actor可以高并发运行。 @@ -2088,9 +2084,9 @@ Actor并发模型的交互原理:各个Actor并发地处理主线程任务, > 以API version 9的工程为例。
API version 8及之前的版本仅支持FA模型,如需使用,注意更换构造Worker的接口和创建worker线程中与主线程通信的对象的两个方法。 ### FA模型 -```js +```ts // main thread(同级目录为例) -import worker from '@ohos.worker'; +import worker, { MessageEvents } from '@ohos.worker'; // 主线程中创建Worker对象 const workerInstance = new worker.ThreadWorker("workers/worker.ts"); @@ -2098,9 +2094,9 @@ const workerInstance = new worker.ThreadWorker("workers/worker.ts"); workerInstance.postMessage("123"); // 主线程接收worker线程信息 -workerInstance.onmessage = function(e) { +workerInstance.onmessage = (e: MessageEvents): void => { // data:worker线程发送的信息 - let data = e.data; + let data: string = e.data; console.log("main thread onmessage"); // 销毁Worker对象 @@ -2108,21 +2104,21 @@ workerInstance.onmessage = function(e) { } // 在调用terminate后,执行回调onexit -workerInstance.onexit = function() { +workerInstance.onexit = () => { console.log("main thread terminate"); } ``` -```js +```ts // worker.ts -import worker from '@ohos.worker'; +import worker, { MessageEvents } from '@ohos.worker'; // 创建worker线程中与主线程通信的对象 const workerPort = worker.workerPort // worker线程接收主线程信息 -workerPort.onmessage = function(e) { +workerPort.onmessage = (e: MessageEvents): void => { // data:主线程发送的信息 - let data = e.data; + let data: string = e.data; console.log("worker.ts onmessage"); // worker线程向主线程发送信息 @@ -2130,7 +2126,7 @@ workerPort.onmessage = function(e) { } // worker线程发生error的回调 -workerPort.onerror= function(e) { +workerPort.onerror= () => { console.log("worker.ts onerror"); } ``` @@ -2145,9 +2141,9 @@ build-profile.json5 配置 : } ``` ### Stage模型 -```js +```ts // main thread(以不同目录为例) -import worker from '@ohos.worker'; +import worker, { MessageEvents } from '@ohos.worker'; // 主线程中创建Worker对象 const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.ts"); @@ -2156,30 +2152,30 @@ const workerInstance = new worker.ThreadWorker("entry/ets/pages/workers/worker.t workerInstance.postMessage("123"); // 主线程接收worker线程信息 -workerInstance.onmessage = function(e) { +workerInstance.onmessage = (e: MessageEvents): void => { // data:worker线程发送的信息 - let data = e.data; + let data: string = e.data; console.log("main thread onmessage"); // 销毁Worker对象 workerInstance.terminate(); } // 在调用terminate后,执行onexit -workerInstance.onexit = function() { +workerInstance.onexit = () => { console.log("main thread terminate"); } ``` -```js +```ts // worker.ts -import worker from '@ohos.worker'; +import worker, { MessageEvents } from '@ohos.worker'; // 创建worker线程中与主线程通信的对象 const workerPort = worker.workerPort // worker线程接收主线程信息 -workerPort.onmessage = function(e) { +workerPort.onmessage = (e: MessageEvents): void => { // data:主线程发送的信息 - let data = e.data; + let data: string = e.data; console.log("worker.ts onmessage"); // worker线程向主线程发送信息 @@ -2187,7 +2183,7 @@ workerPort.onmessage = function(e) { } // worker线程发生error的回调 -workerPort.onerror= function(e) { +workerPort.onerror= () => { console.log("worker.ts onerror"); } ``` -- GitLab