未验证 提交 8645fc6e 编写于 作者: O openharmony_ci 提交者: Gitee

!23059 [monthly0815]:modify taskpool and arkutils adapt to arkts

Merge pull request !23059 from buzhuyu/cherry-pick-1692956535
......@@ -17,16 +17,16 @@ Promise有三种状态:pending(进行中)、fulfilled(已完成)和rej
```js
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const randomNumber = Math.random();
const promise: Promise<number> = new Promise((resolve: Function, reject: Function) => {
setTimeout(() => {
const randomNumber: number = Math.random();
if (randomNumber > 0.5) {
resolve(randomNumber);
} else {
reject(new Error('Random number is too small'));
}
}, 1000);
});
}, 1000);
}
```
上述代码中,setTimeout函数模拟了一个异步操作,并在1秒钟后随机生成一个数字。如果随机数大于0.5,则执行resolve回调函数并将随机数作为参数传递;否则执行reject回调函数并传递一个错误对象作为参数。
......@@ -55,13 +55,13 @@ async函数是一个返回Promise对象的函数,用于表示一个异步操
```js
async function myAsyncFunction() {
const result = await new Promise((resolve) => {
async function myAsyncFunction(): Promise<void> {
const result: string = await new Promise((resolve: Function) => {
setTimeout(() => {
resolve('Hello, world!');
}, 3000);
});
console.info(String(result)); // 输出: Hello, world!
console.info(result); // 输出: Hello, world!
}
myAsyncFunction();
......@@ -73,9 +73,9 @@ myAsyncFunction();
```js
async function myAsyncFunction() {
async function myAsyncFunction(): Promise<void> {
try {
const result = await new Promise((resolve) => {
const result: string = await new Promise((resolve: Function) => {
resolve('Hello, world!');
});
} catch (e) {
......
......@@ -24,19 +24,19 @@ CPU密集型任务是指需要占用系统资源处理大量计算能力的任
import taskpool from '@ohos.taskpool';
@Concurrent
function imageProcessing(dataSlice: ArrayBuffer) {
function imageProcessing(dataSlice: ArrayBuffer): ArrayBuffer {
// 步骤1: 具体的图像处理操作及其他耗时操作
return dataSlice;
}
function histogramStatistic(pixelBuffer: ArrayBuffer) {
function histogramStatistic(pixelBuffer: ArrayBuffer): void {
// 步骤2: 分成三段并发调度
let number = pixelBuffer.byteLength / 3;
let buffer1 = pixelBuffer.slice(0, number);
let buffer2 = pixelBuffer.slice(number, number * 2);
let buffer3 = pixelBuffer.slice(number * 2);
let number: number = pixelBuffer.byteLength / 3;
let buffer1: ArrayBuffer = pixelBuffer.slice(0, number);
let buffer2: ArrayBuffer = pixelBuffer.slice(number, number * 2);
let buffer3: ArrayBuffer = pixelBuffer.slice(number * 2);
let group = new taskpool.TaskGroup();
let group: taskpool.TaskGroup = new taskpool.TaskGroup();
group.addTask(imageProcessing, buffer1);
group.addTask(imageProcessing, buffer2);
group.addTask(imageProcessing, buffer3);
......@@ -83,7 +83,7 @@ struct Index {
```js
import worker from '@ohos.worker';
const workerInstance = 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线程发送消息。
......@@ -93,8 +93,6 @@ struct Index {
```js
// 接收Worker子线程的结果
workerInstance.onmessage = function(e) {
// data:主线程发送的信息
let data = e.data;
console.info('MyWorker.ts onmessage');
// 在Worker线程中进行耗时操作
}
......@@ -140,10 +138,9 @@ struct Index {
}
// Worker线程的onmessage逻辑
workerPort.onmessage = function (e: MessageEvents) {
let data = e.data
workerPort.onmessage = (e: MessageEvents): void => {
// 根据传输的数据的type选择进行操作
switch (data.type) {
switch (e.data.type) {
case 0:
// 进行训练
optimize();
......@@ -152,7 +149,7 @@ struct Index {
break;
case 1:
// 执行预测
const output = predict(data.value);
const output = predict(e.data.value);
// 发送主线程预测的结果
workerPort.postMessage({ type: 'predict', value: output });
break;
......
......@@ -11,21 +11,23 @@ I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/
```ts
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// 定义并发函数,内部密集调用I/O能力
@Concurrent
async function concurrentTest(fileList: string[]) {
// 写入文件的实现
async function write(data, filePath) {
let file = await fs.open(filePath, fs.OpenMode.READ_WRITE);
async function write(data: string, filePath: string): Promise<void> {
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<boolean> {
// 循环写文件操作
for (let i = 0; i < fileList.length; i++) {
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) => {
}).catch((err: BusinessError) => {
console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`)
return false;
})
......@@ -39,12 +41,12 @@ I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/
```ts
import taskpool from '@ohos.taskpool';
let filePath1 = ...; // 应用文件路径
let filePath2 = ...;
let filePath1: string = ...; // 应用文件路径
let filePath2: string = ...;
// 使用TaskPool执行包含密集I/O的并发函数
// 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力
taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => {
taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => {
// 调度结果处理
console.info(`The result: ${ret}`);
})
......
......@@ -202,52 +202,59 @@ Stack进行增、删、改、查操作的常用API如下:
// ArrayList
import ArrayList from '@ohos.util.ArrayList'; // 导入ArrayList模块
let arrayList = new ArrayList();
arrayList.add('a');
arrayList.add(1); // 增加元素
console.info(`result: ${arrayList[0]}`); // 访问元素
arrayList[0] = 'one'; // 修改元素
console.info(`result: ${arrayList[0]}`);
let arrayList1: ArrayList<string> = new ArrayList();
arrayList1.add('a');
let arrayList2: ArrayList<number> = new ArrayList();
arrayList2.add(1); // 增加元素
console.info(`result: ${arrayList2[0]}`); // 访问元素
arrayList1[0] = 'one'; // 修改元素
console.info(`result: ${arrayList1[0]}`);
// Vector
import Vector from '@ohos.util.Vector'; // 导入Vector模块
let vector = new Vector();
vector.add('a');
let vector1: Vector<string> = new Vector();
vector1.add('a');
let vector2: Vector<Array<number>> = new Vector();
let b1 = [1, 2, 3];
vector.add(b1);
vector.add(false); // 增加元素
console.info(`result: ${vector[0]}`); // 访问元素
console.info(`result: ${vector.getFirstElement()}`); // 访问元素
vector2.add(b1);
let vector3: Vector<boolean> = new Vector();
vector3.add(false); // 增加元素
console.info(`result: ${vector1[0]}`); // 访问元素
console.info(`result: ${vector2.getFirstElement()}`); // 访问元素
// Deque
import Deque from '@ohos.util.Deque'; // 导入Deque模块
let deque = new Deque;
deque.insertFront('a');
deque.insertFront(1); // 增加元素
console.info(`result: ${deque[0]}`); // 访问元素
deque[0] = 'one'; // 修改元素
console.info(`result: ${deque[0]}`);
let deque1: Deque<string> = new Deque;
deque1.insertFront('a');
let deque2: Deque<number> = new Deque;
deque2.insertFront(1); // 增加元素
console.info(`result: ${deque1[0]}`); // 访问元素
deque1[0] = 'one'; // 修改元素
console.info(`result: ${deque2[0]}`);
// Stack
import Stack from '@ohos.util.Stack'; // 导入Stack模块
let stack = new Stack();
stack.push('a');
stack.push(1); // 增加元素
console.info(`result: ${stack[0]}`); // 访问元素
stack.pop(); // 弹出元素
console.info(`result: ${stack.length}`);
let stack1: Stack<string> = new Stack();
stack1.push('a');
let stack2: Stack<number> = new Stack();
stack2.push(1); // 增加元素
console.info(`result: ${stack1[0]}`); // 访问元素
stack2.pop(); // 弹出元素
console.info(`result: ${stack2.length}`);
// List
import List from '@ohos.util.List'; // 导入List模块
let list = new List;
list.add('a');
list.add(1);
let list1: List<string> = new List;
list1.add('a');
let list2: List<number> = new List;
list2.add(1);
let list3: List<Array<number>> = new List;
let b2 = [1, 2, 3];
list.add(b2); // 增加元素
console.info(`result: ${list[0]}`); // 访问元素
console.info(`result: ${list.get(0)}`); // 访问元素
list3.add(b2); // 增加元素
console.info(`result: ${list1[0]}`); // 访问元素
console.info(`result: ${list3.get(0)}`); // 访问元素
```
......@@ -29,7 +29,7 @@ Actor并发模型作为基于消息通信并发模型的典型代表,不需要
```js
// 定义可转移对象
let buffer = new ArrayBuffer(100);
let buffer: ArrayBuffer = new ArrayBuffer(100);
```
......@@ -44,7 +44,7 @@ SharedArrayBuffer对象存储的数据在同时被修改时,需要通过原子
```js
// 定义可共享对象,可以使用Atomics进行操作
let sharedBuffer = new SharedArrayBuffer(1024);
let sharedBuffer: SharedArrayBuffer = new SharedArrayBuffer(1024);
```
### Native绑定对象
......
......@@ -216,16 +216,17 @@ PlainArray进行增、删、改、查操作的常用API如下:
// HashMap
import HashMap from '@ohos.util.HashMap'; // 导入HashMap模块
let hashMap = new HashMap();
hashMap.set('a', 123);
hashMap.set(4, 123); // 增加元素
console.info(`result: ${hashMap.hasKey(4)}`); // 判断是否含有某元素
console.info(`result: ${hashMap.get('a')}`); // 访问元素
let hashMap1: HashMap<string, number> = new HashMap();
hashMap1.set('a', 123);
let hashMap2: HashMap<number, number> = new HashMap();
hashMap2.set(4, 123); // 增加元素
console.info(`result: ${hashMap2.hasKey(4)}`); // 判断是否含有某元素
console.info(`result: ${hashMap1.get('a')}`); // 访问元素
// TreeMap
import TreeMap from '@ohos.util.TreeMap'; // 导入TreeMap模块
let treeMap = new TreeMap();
let treeMap: TreeMap<string, number> = new TreeMap();
treeMap.set('a', 123);
treeMap.set('6', 356); // 增加元素
console.info(`result: ${treeMap.get('a')}`); // 访问元素
......@@ -235,7 +236,7 @@ console.info(`result: ${treeMap.getLastKey()}`); // 访问尾元素
// LightWeightMap
import LightWeightMap from '@ohos.util.LightWeightMap'; // 导入LightWeightMap模块
let lightWeightMap = new LightWeightMap();
let lightWeightMap: LightWeightMap<string, number> = new LightWeightMap();
lightWeightMap.set('x', 123);
lightWeightMap.set('8', 356); // 增加元素
console.info(`result: ${lightWeightMap.get('a')}`); // 访问元素
......@@ -245,7 +246,7 @@ console.info(`result: ${lightWeightMap.getIndexOfKey('8')}`); // 访问元素
// PlainArray
import PlainArray from '@ohos.util.PlainArray' // 导入PlainArray模块
let plainArray = new PlainArray();
let plainArray: PlainArray<string> = new PlainArray();
plainArray.add(1, 'sdd');
plainArray.add(2, 'sff'); // 增加元素
console.info(`result: ${plainArray.get(1)}`); // 访问元素
......
......@@ -8,12 +8,13 @@ Promise和async/await提供异步并发能力,适用于单次I/O任务的场
```js
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
async function write(data: string, filePath: string) {
let file = await fs.open(filePath, fs.OpenMode.READ_WRITE);
fs.write(file.fd, data).then((writeLen) => {
async function write(data: string, filePath: string): Promise<void> {
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) => {
}).catch((err: BusinessError) => {
console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`);
})
}
......@@ -22,7 +23,7 @@ Promise和async/await提供异步并发能力,适用于单次I/O任务的场
2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)
```js
let filePath = ...; // 应用文件路径
let filePath: string = ...; // 应用文件路径
write('Hello World!', filePath).then(() => {
console.info('Succeeded in writing data.');
})
......
......@@ -25,18 +25,16 @@
```ts
// Handle.ts 代码
export default class Handle {
static getInstance() {
static getInstance(): void {
// 返回单例对象
}
static syncGet() {
static syncGet(): void {
// 同步Get方法
return;
}
static syncSet(num: number) {
static syncSet(num: number): void {
// 同步Set方法
return;
}
}
```
......@@ -51,7 +49,7 @@ import Handle from './Handle'; // 返回静态句柄
// 步骤1: 定义并发函数,内部调用同步方法
@Concurrent
function func(num: number) {
function func(num: number): boolean {
// 调用静态类对象中实现的同步等待调用
Handle.syncSet(num);
// 或者调用单例对象中实现的同步等待调用
......@@ -60,13 +58,11 @@ function func(num: number) {
}
// 步骤2: 创建任务并执行
async function asyncGet() {
async function asyncGet(): Promise<void> {
// 创建task并传入函数func
let task = new taskpool.Task(func, 1);
// 执行task任务,获取结果res
let res = await taskpool.execute(task);
// 对同步逻辑后的结果进行操作
console.info(String(res));
let task: taskpool.Task = new taskpool.Task(func, 1);
// 执行task任务并对同步逻辑后的结果进行操作
console.info(String(await taskpool.execute(task)));
}
@Entry
......@@ -114,7 +110,7 @@ struct Index {
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let w = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts');
let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts');
w.onmessage = function (d) {
// 接收Worker子线程的结果
}
......
......@@ -102,9 +102,9 @@ TaskPool支持开发者在主线程封装任务抛给任务队列,系统选择
```js
// API 9及之后版本使用:
const worker1 = new worker.ThreadWorker(scriptURL);
const worker1: worker.ThreadWorker = new worker.ThreadWorker(scriptURL);
// API 8及之前版本使用:
const worker1 = new worker.Worker(scriptURL);
const worker1: worker.ThreadWorker = new worker.Worker(scriptURL);
```
构造函数需要传入Worker的路径(scriptURL),Worker文件存放位置默认路径为Worker文件所在目录与pages目录属于同级。
......@@ -119,15 +119,15 @@ const worker1 = new worker.Worker(scriptURL);
```js
// 写法一
// Stage模型-目录同级(entry模块下,workers目录与pages目录同级)
const worker1 = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"});
const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"});
// Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录)
const worker2 = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts');
const worker2: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts');
// 写法二
// Stage模型-目录同级(entry模块下,workers目录与pages目录同级),假设bundlename是com.example.workerdemo
const worker3 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker');
const worker3: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker');
// Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录),假设bundlename是com.example.workerdemo
const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker');
const worker4: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker');
```
......@@ -151,9 +151,9 @@ const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/et
```js
// FA模型-目录同级(entry模块下,workers目录与pages目录同级)
const worker1 = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'});
const worker1: worker.ThreadWorker = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'});
// FA模型-目录不同级(entry模块下,workers目录与pages目录的父目录同级)
const worker2 = new worker.ThreadWorker('../workers/worker.js');
const worker2: worker.ThreadWorker = new worker.ThreadWorker('../workers/worker.js');
```
......
......@@ -25,14 +25,14 @@ XML解析及转换需要确保传入的XML数据符合标准格式。
2. 输入待转换的XML,设置转换选项。
```js
let xml =
let xml: string =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
' <title>Happy</title>' +
' <todo>Work</todo>' +
' <todo>Play</todo>' +
'</note>';
let options = {
let options: convertxml.ConvertOptions = {
// trim: false 转换后是否删除文本前后的空格,否
// declarationKey: "_declaration" 转换后文件声明使用_declaration来标识
// instructionKey: "_instruction" 转换后指令使用_instruction标识
......@@ -51,7 +51,7 @@ XML解析及转换需要确保传入的XML数据符合标准格式。
attributesKey: "_attributes",
textKey: "_text",
cdataKey: "_cdata",
docTypeKey: "_doctype",
doctypeKey: "_doctype",
commentKey: "_comment",
parentKey: "_parent",
typeKey: "_type",
......@@ -63,17 +63,10 @@ XML解析及转换需要确保传入的XML数据符合标准格式。
3. 调用转换函数,打印结果。
```js
let conv = new convertxml.ConvertXML();
let result = conv.convertToJSObject(xml, options);
let strRes = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出
let conv: convertxml.ConvertXML = new convertxml.ConvertXML();
let result: object = conv.convertToJSObject(xml, options);
let strRes: string = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出
console.info(strRes);
// 也可以直接处理转换后的JS对象,获取标签值
let title = result['_elements'][0]['_elements'][0]['_elements'][0]['_text']; // 解析<title>标签对应的值
let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // 解析<todo>标签对应的值
let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // 解析<todo>标签对应的值
console.info(title); // Happy
console.info(todo); // Work
console.info(todo2); // Play
```
输出结果如下所示:
......@@ -86,7 +79,4 @@ XML解析及转换需要确保传入的XML数据符合标准格式。
"_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo",
"_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo",
"_elements":[{"_type":"text","_text":"Play"}]}]}]}
title:Happy
todo:Work
todo2:Play
```
......@@ -33,13 +33,13 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md)
```js
// 1.基于Arraybuffer构造XmlSerializer对象
let arrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区
let thatSer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象
let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区
let thatSer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象
// 2.基于DataView构造XmlSerializer对象
let arrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区
let dataView = new DataView(arrayBuffer); // 使用DataView对象操作ArrayBuffer对象
let thatSer = new xml.XmlSerializer(dataView); // 基于DataView构造XmlSerializer对象
let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区
let dataView: DataView = new DataView(arrayBuffer); // 使用DataView对象操作ArrayBuffer对象
let thatSer: xml.XmlSerializer = new xml.XmlSerializer(dataView); // 基于DataView构造XmlSerializer对象
```
3. 调用XML元素生成函数。
......@@ -66,9 +66,9 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md)
4. 使用Uint8Array操作Arraybuffer,调用TextDecoder对Uint8Array解码后输出。
```js
let view = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据
let textDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类
let res = textDecoder.decodeWithStream(view); // 对view解码
let view: Uint8Array = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据
let textDecoder: util.TextDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类
let res: string = textDecoder.decodeWithStream(view); // 对view解码
console.info(res);
```
......
......@@ -39,27 +39,27 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
```js
let strXml =
let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
'<title>Play</title>' +
'<lens>Work</lens>' +
'</note>';
let textEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
// 1.基于ArrayBuffer构造XmlPullParser对象
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
// 2.基于DataView构造XmlPullParser对象
let dataView = new DataView(arrBuffer.buffer);
let that = new xml.XmlPullParser(dataView, 'UTF-8');
let dataView: DataView = new DataView(arrBuffer.buffer);
let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8');
```
3. 自定义回调函数,本例直接打印出标签及标签值。
```js
let str = '';
function func(name, value){
let str: string = '';
function func(name: string, value: string): boolean {
str = name + value;
console.info(str);
return true; //true:继续解析 false:停止解析
......@@ -69,7 +69,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
4. 设置解析选项,调用parse函数。
```js
let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func};
let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func};
that.parse(options);
```
......@@ -100,23 +100,23 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
2. 对XML文件编码后调用XmlPullParser。
```js
let strXml =
let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
' <title>Play</title>' +
' <title>Happy</title>' +
' <lens>Work</lens>' +
'</note>';
let textEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
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 = '';
function func(name, value){
let str: string = '';
function func(name: string, value: string): boolean {
str += name + ' ' + value + ' ';
return true; // true:继续解析 false:停止解析
}
......@@ -125,7 +125,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
4. 设置解析选项,调用parse函数。
```js
let options = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func};
let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func};
that.parse(options);
console.info(str); // 一次打印出所有的属性及其值
```
......@@ -150,21 +150,21 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
2. 对XML文件编码后调用XmlPullParser。
```js
let strXml =
let strXml: string =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
'<title>Play</title>' +
'</note>';
let textEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
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 = '';
function func(name, value){
let str: string = '';
function func(name: string, value: xml.ParseInfo): boolean {
str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度
console.info(str)
return true; //true:继续解析 false:停止解析
......@@ -174,7 +174,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
4. 设置解析选项,调用parse函数。
```js
let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func};
let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func};
that.parse(options);
```
......@@ -201,36 +201,36 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A
import xml from '@ohos.xml';
import util from '@ohos.util';
let strXml =
let strXml: string =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<book category="COOKING">' +
'<title lang="en">Everyday</title>' +
'<author>Giada</author>' +
'</book>';
let textEncoder = new util.TextEncoder();
let arrBuffer = textEncoder.encodeInto(strXml);
let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
let str = '';
let textEncoder: util.TextEncoder = new util.TextEncoder();
let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml);
let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8');
let str: string = '';
function tagFunc(name, value) {
function tagFunc(name: string, value: string): boolean {
str = name + value;
console.info('tag-' + str);
return true;
}
function attFunc(name, value) {
function attFunc(name: string, value: string): boolean {
str = name + ' ' + value;
console.info('attri-' + str);
return true;
}
function tokenFunc(name, value) {
function tokenFunc(name: string, value: xml.ParseInfo): boolean {
str = name + ' ' + value.getDepth();
console.info('token-' + str);
return true;
}
let options = {
let options: xml.ParseOptions = {
supportDocType: true,
ignoreNameSpace: true,
tagValueCallbackFunction: tagFunc,
......
......@@ -51,12 +51,12 @@ execute(func: Function, ...args: unknown[]): Promise\<unknown>
```ts
@Concurrent
function printArgs(args) {
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
taskpool.execute(printArgs, 100).then((value) => { // 100: test number
taskpool.execute(printArgs, 100).then((value: number) => { // 100: test number
console.log("taskpool result: " + value);
});
```
......@@ -96,13 +96,13 @@ execute(task: Task, priority?: Priority): Promise\<unknown>
```ts
@Concurrent
function printArgs(args) {
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
let task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.execute(task).then((value) => {
let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.execute(task).then((value: number) => {
console.log("taskpool result: " + value);
});
```
......@@ -140,32 +140,28 @@ execute(group: TaskGroup, priority?: Priority): Promise<unknown[]>
```ts
@Concurrent
function printArgs(args) {
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
let taskGroup1 = new taskpool.TaskGroup();
let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
taskGroup1.addTask(printArgs, 20); // 20: test number
taskGroup1.addTask(printArgs, 30); // 30: test number
let taskGroup2 = new taskpool.TaskGroup();
let task1 = new taskpool.Task(printArgs, 100); // 100: test number
let task2 = new taskpool.Task(printArgs, 200); // 200: test number
let task3 = new taskpool.Task(printArgs, 300); // 300: test number
let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1);
taskGroup2.addTask(task2);
taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res) => {
taskpool.execute(taskGroup1).then((res: Array<number>) => {
console.info("taskpool execute res is:" + res);
}).catch((e) => {
console.error("taskpool execute error is:" + e);
});
taskpool.execute(taskGroup2).then((res) => {
taskpool.execute(taskGroup2).then((res: Array<number>) => {
console.info("taskpool execute res is:" + res);
}).catch((e) => {
console.error("taskpool execute error is:" + e);
});
```
......@@ -198,14 +194,14 @@ cancel(task: Task): void
```ts
@Concurrent
function inspectStatus(arg) {
function inspectStatus(arg: number): number {
// 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled before 2s sleep.");
return arg + 2;
}
// 2s sleep
let t = Date.now();
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
......@@ -217,22 +213,20 @@ function inspectStatus(arg) {
return arg + 1;
}
let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number
let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number
let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number
let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number
let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number
let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number
taskpool.execute(task1).then((res)=>{
let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number
let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number
let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number
let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number
let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number
taskpool.execute(task1).then((res: number)=>{
console.log("taskpool test result: " + res);
}).catch((err) => {
console.log("taskpool test occur error: " + err);
});
let res2 = taskpool.execute(task2);
let res3 = taskpool.execute(task3);
let res4 = taskpool.execute(task4);
let res5 = taskpool.execute(task5);
let res6 = taskpool.execute(task6);
taskpool.execute(task2);
taskpool.execute(task3);
taskpool.execute(task4);
taskpool.execute(task5);
taskpool.execute(task6);
// 1s后取消task
setTimeout(()=>{
taskpool.cancel(task1);}, 1000);
......@@ -264,8 +258,8 @@ cancel(group: TaskGroup): void
```ts
@Concurrent
function printArgs(args) {
let t = Date.now();
function printArgs(args: number): number {
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
......@@ -273,14 +267,14 @@ function printArgs(args) {
return args;
}
let taskGroup1 = new taskpool.TaskGroup();
let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
let taskGroup2 = new taskpool.TaskGroup();
let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup2.addTask(printArgs, 100); // 100: test number
taskpool.execute(taskGroup1).then((res)=>{
taskpool.execute(taskGroup1).then((res: Array<number>)=>{
console.info("taskGroup1 res is:" + res)
});
taskpool.execute(taskGroup2).then((res)=>{
taskpool.execute(taskGroup2).then((res: Array<number>)=>{
console.info("taskGroup2 res is:" + res)
});
setTimeout(()=>{
......@@ -310,7 +304,7 @@ getTaskPoolInfo(): TaskPoolInfo
**示例:**
```ts
let taskpoolInfo = taskpool.getTaskPoolInfo();
let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
```
## Priority
......@@ -329,35 +323,29 @@ let taskpoolInfo = taskpool.getTaskPoolInfo();
```ts
@Concurrent
function printArgs(args) {
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
let task = new taskpool.Task(printArgs, 100); // 100: test number
let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let highCount = 0;
let mediumCount = 0;
let lowCount = 0;
let allCount = 100;
for (let i = 0; i < allCount; i++) {
for (let i: number = 0; i < allCount; i++) {
taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => {
lowCount++;
console.log("taskpool lowCount is :" + lowCount);
}).catch((e) => {
console.error("low task error: " + e);
})
});
taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => {
mediumCount++;
console.log("taskpool mediumCount is :" + mediumCount);
}).catch((e) => {
console.error("medium task error: " + e);
})
});
taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => {
highCount++;
console.log("taskpool highCount is :" + highCount);
}).catch((e) => {
console.error("high task error: " + e);
})
});
}
```
......@@ -392,12 +380,12 @@ Task的构造函数。
```ts
@Concurrent
function printArgs(args) {
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
let task = new taskpool.Task(printArgs, "this is my first Task");
let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task");
```
### isCanceled<sup>10+</sup>
......@@ -418,7 +406,7 @@ static isCanceled(): boolean
```ts
@Concurrent
function inspectStatus(arg) {
function inspectStatus(arg: number): number {
// do something
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled.");
......@@ -437,14 +425,14 @@ function inspectStatus(arg) {
```ts
@Concurrent
function inspectStatus(arg) {
function inspectStatus(arg: number): number {
// 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled before 2s sleep.");
return arg + 2;
}
// 延时2s
let t = Date.now();
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
......@@ -456,10 +444,10 @@ function inspectStatus(arg) {
return arg + 1;
}
let task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res)=>{
let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res: number)=>{
console.log("taskpool test result: " + res);
}).catch((err) => {
}).catch((err: string) => {
console.log("taskpool test occur error: " + err);
});
// 不调用cancel,isCanceled()默认返回false,task执行的结果为101
......@@ -485,24 +473,24 @@ setTransferList(transfer?: ArrayBuffer[]): void
**示例:**
```ts
let buffer = new ArrayBuffer(8);
let view = new Uint8Array(buffer);
let buffer1 = new ArrayBuffer(16);
let view1 = new Uint8Array(buffer1);
let buffer: ArrayBuffer = new ArrayBuffer(8);
let view: Uint8Array = new Uint8Array(buffer);
let buffer1: ArrayBuffer = new ArrayBuffer(16);
let view1: Uint8Array = new Uint8Array(buffer1);
console.info("testTransfer view byteLength: " + view.byteLength);
console.info("testTransfer view1 byteLength: " + view1.byteLength);
@Concurrent
function testTransfer(arg1, arg2) {
function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number {
console.info("testTransfer arg1 byteLength: " + arg1.byteLength);
console.info("testTransfer arg2 byteLength: " + arg2.byteLength);
return 100;
}
let task = new taskpool.Task(testTransfer, view, view1);
let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1);
task.setTransferList([view.buffer, view1.buffer]);
taskpool.execute(task).then((res)=>{
taskpool.execute(task).then((res: number)=>{
console.info("test result: " + res);
}).catch((e)=>{
}).catch((e: string)=>{
console.error("test catch: " + e);
})
console.info("testTransfer view byteLength: " + view.byteLength);
......@@ -563,12 +551,12 @@ addTask(func: Function, ...args: unknown[]): void
```ts
@Concurrent
function printArgs(args) {
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
let taskGroup = new taskpool.TaskGroup();
let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup.addTask(printArgs, 100); // 100: test number
```
......@@ -598,13 +586,13 @@ addTask(task: Task): void
```ts
@Concurrent
function printArgs(args) {
function printArgs(args: number): number {
console.log("printArgs: " + args);
return args;
}
let taskGroup = new taskpool.TaskGroup();
let task = new taskpool.Task(printArgs, 200); // 200: test number
let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
taskGroup.addTask(task);
```
......@@ -675,12 +663,6 @@ taskGroup.addTask(task);
### 序列化支持类型
序列化支持类型包括:All Primitive Type(不包括symbol)、Date、String、RegExp、Array、Map、Set、Object、ArrayBuffer、TypedArray。
### 注意事项
- 仅支持在Stage模型且module的compileMode为esmodule的project中使用taskpool api。确认module的compileMode方法:查看当前module的build-profile.json5,在buildOption中补充"compileMode": "esmodule"。
- taskpool任务只支持引用入参传递或者import的变量,不支持使用闭包变量,使用装饰器@Concurrent进行拦截。
- taskpool任务只支持普通函数或者async函数,不支持类成员函数或者匿名函数,使用装饰器@Concurrent进行拦截。
- 装饰器@Concurrent仅支持在ets文件使用。
### 简单使用
**示例一**
......@@ -688,22 +670,17 @@ taskGroup.addTask(task);
```ts
// 支持普通函数、引用入参传递
@Concurrent
function printArgs(args) {
function printArgs(args: number): number {
console.log("func: " + args);
return args;
}
async function taskpoolExecute() {
async function taskpoolExecute(): Promise<void> {
// taskpool.execute(task)
let task = new taskpool.Task(printArgs, "create task, then execute");
let val1 = await taskpool.execute(task);
console.log("taskpool.execute(task) result: " + val1);
let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
console.log("taskpool.execute(task) result: " + await taskpool.execute(task));
// taskpool.execute(function)
let val2 = await taskpool.execute(printArgs, "execute task by func");
console.log("taskpool.execute(function) result: " + val2);
console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
}
taskpoolExecute();
```
......@@ -711,7 +688,7 @@ taskpoolExecute();
```ts
// b.ets
export let c = 2000;
export let c: number = 2000;
```
```ts
// 引用import变量
......@@ -719,7 +696,7 @@ export let c = 2000;
import { c } from "./b";
@Concurrent
function printArgs(a) {
function printArgs(a: number): number {
console.log(a);
console.log(c);
return a;
......@@ -727,13 +704,11 @@ function printArgs(a) {
async function taskpoolExecute() {
// taskpool.execute(task)
let task = new taskpool.Task(printArgs, "create task, then execute");
let val1 = await taskpool.execute(task);
console.log("taskpool.execute(task) result: " + val1);
let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
console.log("taskpool.execute(task) result: " + await taskpool.execute(task));
// taskpool.execute(function)
let val2 = await taskpool.execute(printArgs, "execute task by func");
console.log("taskpool.execute(function) result: " + val2);
console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
}
taskpoolExecute();
......@@ -752,8 +727,10 @@ async function delayExcute() {
}
async function taskpoolExecute() {
taskpool.execute(delayExcute).then((result) => {
console.log("TaskPoolTest task result: " + result);
taskpool.execute(delayExcute).then((result: string) => {
console.log("taskPoolTest task result: " + result);
}).catch((err: string) => {
console.log("taskpool test occur error: " + err);
});
}
......@@ -765,23 +742,24 @@ taskpoolExecute();
```ts
// c.ets
@Concurrent
function strSort(inPutArr) {
function strSort(inPutArr: Array<string>): Array<string> {
let newArr = inPutArr.sort();
return newArr;
}
export async function func1() {
console.log("taskpoolTest start");
let strArray = ['c test string', 'b test string', 'a test string'];
let task = new taskpool.Task(strSort, strArray);
let result = await taskpool.execute(task);
console.log("func1 result:" + result);
let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
let task: taskpool.Task = new taskpool.Task(strSort, strArray);
console.log("func1 result:" + await taskpool.execute(task));
}
export async function func2() {
console.log("taskpoolTest2 start");
let strArray = ['c test string', 'b test string', 'a test string'];
taskpool.execute(strSort, strArray).then((result) => {
let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
taskpool.execute(strSort, strArray).then((result: Array<string>) => {
console.log("func2 result: " + result);
}).catch((err: string) => {
console.log("taskpool test occur error: " + err);
});
}
```
......@@ -799,14 +777,14 @@ func2();
```ts
// 任务取消成功
@Concurrent
function inspectStatus(arg) {
function inspectStatus(arg: number): number {
// 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled before 2s sleep.");
return arg + 2;
}
// 2s sleep
let t = Date.now();
let t: number = Date.now();
while (Date.now() - t < 2000) {
continue;
}
......@@ -818,11 +796,11 @@ function inspectStatus(arg) {
return arg + 1;
}
async function taskpoolCancel() {
let task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res)=>{
async function taskpoolCancel(): Promise<void> {
let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res: number)=>{
console.log("taskpool test result: " + res);
}).catch((err) => {
}).catch((err: string) => {
console.log("taskpool test occur error: " + err);
});
// 1s后取消task
......@@ -838,14 +816,14 @@ taskpoolCancel();
```ts
// 已执行的任务取消失败
@Concurrent
function inspectStatus(arg) {
function inspectStatus(arg: number): number {
// 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) {
return arg + 2;
}
// 延时2s
let t = Date.now();
while (Date.now() - t < 2000) {
let t: number = Date.now();
while (Date.now() - t < 500) {
continue;
}
// 第二次检查取消并作出响应
......@@ -855,13 +833,14 @@ function inspectStatus(arg) {
return arg + 1;
}
async function taskpoolCancel() {
let task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res)=>{
async function taskpoolCancel(): Promise<void> {
let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
taskpool.execute(task).then((res: number)=>{
console.log("taskpool test result: " + res);
}).catch((err) => {
}).catch((err: string) => {
console.log("taskpool test occur error: " + err);
});
setTimeout(()=>{
try {
taskpool.cancel(task); // 任务已执行,取消失败
......@@ -879,8 +858,8 @@ taskpoolCancel();
```ts
// 待执行的任务组取消成功
@Concurrent
function printArgs(args) {
let t = Date.now();
function printArgs(args: number): number {
let t: number = Date.now();
while (Date.now() - t < 1000) {
continue;
}
......@@ -888,26 +867,26 @@ function printArgs(args) {
return args;
}
async function taskpoolGroupCancelTest() {
let taskGroup1 = new taskpool.TaskGroup();
async function taskpoolGroupCancelTest(): Promise<void> {
let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
taskGroup1.addTask(printArgs, 20); // 20: test number
taskGroup1.addTask(printArgs, 30); // 30: test number
let taskGroup2 = new taskpool.TaskGroup();
let task1 = new taskpool.Task(printArgs, 100); // 100: test number
let task2 = new taskpool.Task(printArgs, 200); // 200: test number
let task3 = new taskpool.Task(printArgs, 300); // 300: test number
let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1);
taskGroup2.addTask(task2);
taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res) => {
taskpool.execute(taskGroup1).then((res: Array<number>) => {
console.info("taskpool execute res is:" + res);
}).catch((e) => {
}).catch((e: string) => {
console.error("taskpool execute error is:" + e);
});
taskpool.execute(taskGroup2).then((res) => {
taskpool.execute(taskGroup2).then((res: Array<number>) => {
console.info("taskpool execute res is:" + res);
}).catch((e) => {
}).catch((e: string) => {
console.error("taskpool execute error is:" + e);
});
......@@ -922,48 +901,48 @@ taskpoolGroupCancelTest()
```ts
// 分别创建执行100个高、中、低优先级的任务,查看其各项信息
@Concurrent
function delay() {
let start = new Date().getTime();
function delay(): void {
let start: number = new Date().getTime();
while (new Date().getTime() - start < 500) {
continue;
}
}
let highCount = 0;
let mediumCount = 0;
let lowCount = 0;
let allCount = 100;
let highCount: number = 0;
let mediumCount: number = 0;
let lowCount: number = 0;
let allCount: number = 100;
for (let i = 0; i < allCount; i++) {
let task1 = new taskpool.Task(delay);
let task2 = new taskpool.Task(delay);
let task3 = new taskpool.Task(delay);
let task1: taskpool.Task = new taskpool.Task(delay);
let task2: taskpool.Task = new taskpool.Task(delay);
let task3: taskpool.Task = new taskpool.Task(delay);
taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
lowCount++;
}).catch((e) => {
}).catch((e: string) => {
console.error("low task error: " + e);
})
taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
mediumCount++;
}).catch((e) => {
}).catch((e: string) => {
console.error("medium task error: " + e);
})
taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
highCount++;
}).catch((e) => {
}).catch((e: string) => {
console.error("high task error: " + e);
})
}
let start = new Date().getTime();
let start: number = new Date().getTime();
while (new Date().getTime() - start < 1000) {
continue;
}
let taskpoolInfo = taskpool.getTaskPoolInfo();
let tid = 0;
let taskIds = [];
let priority = 0;
let taskId = 0;
let state = 0;
let duration = 0;
let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
let tid: number = 0;
let taskIds: Array<number> = [];
let priority: number = 0;
let taskId: number = 0;
let state: number = 0;
let duration: number = 0;
for(let threadInfo of taskpoolInfo.threadInfos) {
tid = threadInfo.tid;
taskIds.length = threadInfo.taskIds.length;
......
......@@ -2083,17 +2083,6 @@ Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程
Actor并发模型的交互原理:各个Actor并发地处理主线程任务,每个Actor内部都有一个消息队列及单线程执行模块,消息队列负责接收主线程及其他Actor的请求,单线程执行模块则负责串行地处理请求、向其他Actor发送请求以及创建新的Actor。由于Actor采用的是异步方式,各个Actor之间相互隔离没有数据竞争,因此Actor可以高并发运行。
### 注意事项
- Worker存在数量限制,当前支持最多同时存在8个Worker。
- 在API version 8及之前的版本,当Worker数量超出限制时,会抛出错误Error "Too many workers, the number of workers exceeds the maximum."。
- 从API version 9开始,当Worker数量超出限制时,会抛出错误BusinessError "Worker initialization failure, the number of workers exceeds the maximum."。
- 主动销毁Worker可以调用新创建Worker对象的terminate()或workerPort.close()方法。
- 自API version 9版本开始,若Worker处于已经销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的BusinessError。
- Worker的创建和销毁耗费性能,建议管理已创建的Worker并重复使用。
- 创建Worker工程时,new worker.Worker构造函数和new worker.ThreadWorker构造函数不能同时使用,否则将导致工程中Worker的功能异常。自API version 9版本开始,建议使用[new worker.ThreadWorker](#constructor9)构造函数,在API version 8及之前的版本,建议使用[new worker.Worker](#constructordeprecated)构造函数。
- 创建Worker工程时,在Worker线程的文件中(比如本文中worker.ts)不能导入任何有关构建UI的方法(比如ets文件等),否则会导致Worker的功能失效。排查方式:解压生成的Hap包,在创建Worker线程的文件目录中找到"worker.js",全局搜索"View"关键字。如果存在该关键字,说明在worker.js中打包进去了构建UI的方法,会导致Worker的功能失效,建议在创建Worker线程的文件中修改 "import “xxx” from src"中src的目录层级。
- 线程间通信时传递的数据量最大限制为16M。
## 完整示例
> **说明:**<br/>
> 以API version 9的工程为例。<br> API version 8及之前的版本仅支持FA模型,如需使用,注意更换构造Worker的接口和创建worker线程中与主线程通信的对象的两个方法。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册