• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.taskpool (Starting the Task Pool)
2
3The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance.
4
5You can determine the execution sequence of tasks with the same priority. They are executed in the same sequence as you call the task execution APIs. The default task priority is **MEDIUM**.
6
7If the number of tasks to be executed is greater than the number of worker threads in the task pool, the task pool scales out based on load balancing to minimize the waiting duration. Similarly, when the number of tasks to be executed falls below the number of worker threads, the task pool scales in to reduce the number of worker threads.
8
9The **TaskPool** APIs return error codes in numeric format. For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
10
11For details about the precautions for using **TaskPool**, see [Precautions for TaskPool](../../arkts-utils/taskpool-introduction.md#precautions-for-taskpool).
12
13> **NOTE**<br>
14> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
15
16## Modules to Import
17
18```ts
19import taskpool from '@ohos.taskpool';
20```
21## taskpool.execute
22
23execute(func: Function, ...args: Object[]): Promise\<Object>
24
25Places the function to be executed in the internal queue of the task pool. The function will be distributed to the worker thread for execution. The function to be executed in this mode cannot be canceled.
26
27**System capability**: SystemCapability.Utils.Lang
28
29**Parameters**
30
31| Name| Type     | Mandatory| Description                                                                  |
32| ------ | --------- | ---- | ---------------------------------------------------------------------- |
33| func   | Function  | Yes  | Function to be executed. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
34| args   | Object[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
35
36**Return value**
37
38| Type             | Description                                |
39| ----------------- | ------------------------------------ |
40| Promise\<Object>  | Promise used to return an object that carries the function execution result.|
41
42**Error codes**
43
44For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
45
46| ID| Error Message                                     |
47| -------- | -------------------------------------------- |
48| 10200003 | Worker initialization failure.               |
49| 10200006 | An exception occurred during serialization.  |
50| 10200014 | The function is not mark as concurrent.      |
51
52**Example**
53
54```ts
55@Concurrent
56function printArgs(args: number): number {
57    console.info("printArgs: " + args);
58    return args;
59}
60
61taskpool.execute(printArgs, 100).then((value: Object) => { // 100: test number
62  console.info("taskpool result: " + value);
63});
64```
65
66## taskpool.execute
67
68execute(task: Task, priority?: Priority): Promise\<Object>
69
70Places a task in the internal queue of the task pool. The task will be distributed to the worker thread for execution. The task to be executed in this mode can be canceled. The task cannot be a task in a task group or queue.
71
72**System capability**: SystemCapability.Utils.Lang
73
74**Parameters**
75
76| Name  | Type                 | Mandatory| Description                                      |
77| -------- | --------------------- | ---- | ---------------------------------------- |
78| task     | [Task](#task)         | Yes  | Task to be executed.                 |
79| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
80
81**Return value**
82
83| Type             | Description             |
84| ----------------  | ---------------- |
85| Promise\<Object> | Promise used to return an object that carries the function execution result.|
86
87**Error codes**
88
89For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
90
91| ID| Error Message                                    |
92| -------- | ------------------------------------------- |
93| 10200003 | Worker initialization failure.              |
94| 10200006 | An exception occurred during serialization. |
95| 10200014 | The function is not mark as concurrent.     |
96
97**Example**
98
99```ts
100@Concurrent
101function printArgs(args: number): number {
102    console.info("printArgs: " + args);
103    return args;
104}
105
106let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
107taskpool.execute(task).then((value: Object) => {
108  console.info("taskpool result: " + value);
109});
110```
111
112## taskpool.execute<sup>10+</sup>
113
114execute(group: TaskGroup, priority?: Priority): Promise<Object[]>
115
116Places a task group in the internal queue of the task pool. The task group will be distributed to the worker thread for execution.
117
118**System capability**: SystemCapability.Utils.Lang
119
120**Parameters**
121
122| Name    | Type                       | Mandatory| Description                                                          |
123| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
124| group     | [TaskGroup](#taskgroup10)     | Yes  | Task group to be executed.                                     |
125| priority  | [Priority](#priority)       | No  | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.|
126
127**Return value**
128
129| Type                | Description                              |
130| ----------------    | ---------------------------------- |
131| Promise\<Object[]>  | Promise used to return an object array that carries the function execution result.|
132
133**Error codes**
134
135For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
136
137| ID| Error Message                                    |
138| -------- | ------------------------------------------- |
139| 10200006 | An exception occurred during serialization. |
140
141**Example**
142
143```ts
144@Concurrent
145function printArgs(args: number): number {
146    console.info("printArgs: " + args);
147    return args;
148}
149
150let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
151taskGroup1.addTask(printArgs, 10); // 10: test number
152taskGroup1.addTask(printArgs, 20); // 20: test number
153taskGroup1.addTask(printArgs, 30); // 30: test number
154
155let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
156let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
157let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
158let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
159taskGroup2.addTask(task1);
160taskGroup2.addTask(task2);
161taskGroup2.addTask(task3);
162taskpool.execute(taskGroup1).then((res: Array<Object>) => {
163  console.info("taskpool execute res is:" + res);
164});
165taskpool.execute(taskGroup2).then((res: Array<Object>) => {
166  console.info("taskpool execute res is:" + res);
167});
168```
169
170## taskpool.executeDelayed<sup>11+</sup>
171
172executeDelayed(delayTime: number, task: Task, priority?: Priority): Promise\<Object>
173
174Executes a task after a given delay. The task cannot be a task in a task group or queue.
175
176**System capability**: SystemCapability.Utils.Lang
177
178**Parameters**
179
180| Name      | Type         | Mandatory| Description                |
181| ----------- | ------------- | ---- | -------------------- |
182| delayTime   | number        | Yes  | Delay, in ms. |
183| task        | [Task](#task) | Yes  | Task to delay.|
184| priority    | [Priority](#priority)       | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
185
186**Return value**
187
188| Type                | Description                              |
189| ----------------    | ---------------------------------- |
190| Promise\<Object>  | Promise used to return an object array that carries the function execution result.|
191
192**Error codes**
193
194For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
195
196| ID  | Error Message                        |
197| --------- | -------------------------------- |
198| 10200028 | The delayTime is less than zero. |
199
200**Example**
201
202```ts
203@Concurrent
204// import BusinessError
205import { BusinessError } from '@ohos.base'
206
207function printArgs(args: number): void {
208    console.info("printArgs: " + args);
209}
210
211let t: number = Date.now();
212console.info("taskpool start time is: " + t);
213let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
214taskpool.executeDelayed(1000, task).then(() => { // 1000:delayTime is 1000ms
215  console.info("taskpool execute success");
216}).catch((e: BusinessError) => {
217  console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`);
218})
219```
220
221
222## taskpool.cancel
223
224cancel(task: Task): void
225
226Cancels a task in the task pool.
227
228**System capability**: SystemCapability.Utils.Lang
229
230**Parameters**
231
232| Name| Type         | Mandatory| Description                |
233| ------ | ------------- | ---- | -------------------- |
234| task   | [Task](#task) | Yes  | Task to cancel.|
235
236**Error codes**
237
238For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
239
240| ID| Error Message                                     |
241| -------- | -------------------------------------------- |
242| 10200015 | The task does not exist when it is canceled. |
243| 10200016 | The task is executing when it is canceled.   |
244
245Since API version 10, error code 10200016 is not reported when this API is called.
246
247**Example of canceling an ongoing task**
248
249```ts
250@Concurrent
251function inspectStatus(arg: number): number {
252  // Check whether the task has been canceled and respond accordingly.
253  if (taskpool.Task.isCanceled()) {
254    console.info("task has been canceled before 2s sleep.");
255    return arg + 2;
256  }
257  // 2s sleep
258  let t: number = Date.now();
259  while (Date.now() - t < 2000) {
260    continue;
261  }
262  // Check again whether the task has been canceled and respond accordingly.
263  if (taskpool.Task.isCanceled()) {
264    console.info("task has been canceled after 2s sleep.");
265    return arg + 3;
266  }
267  return arg + 1;
268}
269
270let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
271let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number
272let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number
273let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number
274let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number
275let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number
276taskpool.execute(task1).then((res: Object)=>{
277  console.info("taskpool test result: " + res);
278});
279taskpool.execute(task2);
280taskpool.execute(task3);
281taskpool.execute(task4);
282taskpool.execute(task5);
283taskpool.execute(task6);
284// Cancel the task 1s later.
285setTimeout(()=>{
286  taskpool.cancel(task1);
287}, 1000);
288```
289
290## taskpool.cancel<sup>10+</sup>
291
292cancel(group: TaskGroup): void
293
294Cancels a task group in the task pool.
295
296**System capability**: SystemCapability.Utils.Lang
297
298**Parameters**
299
300| Name  | Type                   | Mandatory| Description                |
301| ------- | ----------------------- | ---- | -------------------- |
302| group   | [TaskGroup](#taskgroup10) | Yes  | Task group to cancel.|
303
304**Error codes**
305
306For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
307
308| ID| Error Message                                                |
309| -------- | ------------------------------------------------------- |
310| 10200018 | The task group does not exist when it is canceled.      |
311
312**Example**
313
314```ts
315@Concurrent
316function printArgs(args: number): number {
317  let t: number = Date.now();
318  while (Date.now() - t < 2000) {
319    continue;
320  }
321  console.info("printArgs: " + args);
322  return args;
323}
324
325let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
326taskGroup1.addTask(printArgs, 10); // 10: test number
327let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
328taskGroup2.addTask(printArgs, 100); // 100: test number
329taskpool.execute(taskGroup1).then((res: Array<Object>)=>{
330  console.info("taskGroup1 res is:" + res);
331});
332taskpool.execute(taskGroup2).then((res: Array<Object>)=>{
333  console.info("taskGroup2 res is:" + res);
334});
335setTimeout(()=>{
336  try {
337    taskpool.cancel(taskGroup2);
338  } catch (e) {
339    console.error("taskGroup.cancel occur error:" + e);
340  }
341}, 1000);
342```
343
344
345## taskpool.getTaskPoolInfo<sup>10+</sup>
346
347getTaskPoolInfo(): TaskPoolInfo
348
349Obtains the internal information about this task pool.
350
351**System capability**: SystemCapability.Utils.Lang
352
353**Return value**
354
355| Type                               | Description               |
356| ----------------------------------- | ------------------ |
357| [TaskPoolInfo](#taskpoolinfo10)   | Internal information about the task pool.  |
358
359**Example**
360
361```ts
362let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
363```
364
365## Priority
366
367Enumerates the priorities available for created tasks.
368
369**System capability**: SystemCapability.Utils.Lang
370
371| Name| Value| Description|
372| -------- | -------- | -------- |
373| HIGH   | 0    | The task has a high priority.|
374| MEDIUM | 1 | The task has a medium priority.|
375| LOW | 2 | The task has a low priority.|
376
377**Example**
378
379```ts
380@Concurrent
381function printArgs(args: number): number {
382  console.info("printArgs: " + args);
383  return args;
384}
385
386let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
387let highCount = 0;
388let mediumCount = 0;
389let lowCount = 0;
390let allCount = 100;
391for (let i: number = 0; i < allCount; i++) {
392  taskpool.execute(task, taskpool.Priority.LOW).then((res: Object) => {
393    lowCount++;
394    console.info("taskpool lowCount is :" + lowCount);
395  });
396  taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: Object) => {
397    mediumCount++;
398    console.info("taskpool mediumCount is :" + mediumCount);
399  });
400  taskpool.execute(task, taskpool.Priority.HIGH).then((res: Object) => {
401    highCount++;
402    console.info("taskpool highCount is :" + highCount);
403  });
404}
405```
406
407## Task
408
409Implements a task. Before calling any APIs in **Task**, you must use [constructor](#constructor) to create a **Task** instance.
410
411### constructor
412
413constructor(func: Function, ...args: Object[])
414
415A constructor used to create a **Task** instance.
416
417**System capability**: SystemCapability.Utils.Lang
418
419**Parameters**
420
421| Name| Type     | Mandatory| Description                                                                 |
422| ------ | --------- | ---- | -------------------------------------------------------------------- |
423| func   | Function  | Yes  | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).  |
424| args   | Object[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
425
426**Error codes**
427
428For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
429
430| ID| Error Message                                |
431| -------- | --------------------------------------- |
432| 10200014 | The function is not mark as concurrent. |
433
434**Example**
435
436```ts
437@Concurrent
438function printArgs(args: number): number {
439  console.info("printArgs: " + args);
440  return args;
441}
442
443let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task");
444```
445
446### constructor<sup>11+</sup>
447
448constructor(name: string, func: Function, ...args: Object[])
449
450A constructor used to create a **Task** instance, with the task name specified.
451
452**System capability**: SystemCapability.Utils.Lang
453
454**Parameters**
455
456| Name| Type    | Mandatory| Description                                                        |
457| ------ | -------- | ---- | ------------------------------------------------------------ |
458| name   | string   | Yes  | Task name.                                                  |
459| func   | Function | Yes  | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).|
460| args   | Object[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
461
462**Error codes**
463
464For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
465
466| ID| Error Message                               |
467| -------- | --------------------------------------- |
468| 10200014 | The function is not mark as concurrent. |
469
470**Example**
471
472```ts
473@Concurrent
474function printArgs(args: string): string {
475  console.info("printArgs: " + args);
476  return args;
477}
478
479let taskName: string = "taskName";
480let task: taskpool.Task = new taskpool.Task(taskName, printArgs, "this is my first Task");
481let name: string = task.name;
482```
483
484### isCanceled<sup>10+</sup>
485
486static isCanceled(): boolean
487
488Checks whether the running task is canceled. Before using this API, you must create a **Task** instance.
489
490**System capability**: SystemCapability.Utils.Lang
491
492**Return value**
493
494| Type   | Description                                |
495| ------- | ------------------------------------ |
496| boolean | Returns **true** if the running task is canceled; returns **false** otherwise.|
497
498**Example**
499
500```ts
501@Concurrent
502function inspectStatus(arg: number): number {
503    // do something
504    if (taskpool.Task.isCanceled()) {
505      console.info("task has been canceled.");
506      // do something
507      return arg + 1;
508    }
509    // do something
510    return arg;
511}
512```
513
514> **NOTE**<br>
515> **isCanceled** must be used together with **taskpool.cancel**. If **cancel** is not called, **isCanceled** returns **false** by default.
516
517**Example**
518
519```ts
520@Concurrent
521function inspectStatus(arg: number): number {
522  // Check whether the task has been canceled and respond accordingly.
523  if (taskpool.Task.isCanceled()) {
524    console.info("task has been canceled before 2s sleep.");
525    return arg + 2;
526  }
527  // Wait for 2s.
528  let t: number = Date.now();
529  while (Date.now() - t < 2000) {
530    continue;
531  }
532  // Check again whether the task has been canceled and respond accordingly.
533  if (taskpool.Task.isCanceled()) {
534    console.info("task has been canceled after 2s sleep.");
535    return arg + 3;
536  }
537  return arg + 1;
538}
539
540let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
541taskpool.execute(task).then((res: Object)=>{
542  console.info("taskpool test result: " + res);
543}).catch((err: string) => {
544  console.error("taskpool test occur error: " + err);
545});
546// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101.
547```
548
549### setTransferList<sup>10+</sup>
550
551setTransferList(transfer?: ArrayBuffer[]): void
552
553Sets the task transfer list. Before using this API, you must create a **Task** instance.
554
555> **NOTE**<br>
556> This API is used to set the task transfer list in the form of **ArrayBuffer** in the task pool. The **ArrayBuffer** instance does not copy the content in the task to the worker thread during transfer. Instead, it transfers the buffer control right to the worker thread. After the transfer, the **ArrayBuffer** instance becomes invalid. An empty **ArrayBuffer** will not be transferred.
557
558**System capability**: SystemCapability.Utils.Lang
559
560**Parameters**
561
562| Name  | Type          | Mandatory| Description                                         |
563| -------- | ------------- | ---- | --------------------------------------------- |
564| transfer | ArrayBuffer[] | No  | **ArrayBuffer** instance holding the objects to transfer. The default value is an empty array.|
565
566**Error codes**
567
568For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
569
570| ID| Error Message                                                       |
571| -------- | -------------------------------------------------------------- |
572| 10200029 | Can not set an arraybuffer to both transferList and cloneList. |
573
574**Example**
575
576```ts
577@Concurrent
578function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number {
579  console.info("testTransfer arg1 byteLength: " + arg1.byteLength);
580  console.info("testTransfer arg2 byteLength: " + arg2.byteLength);
581  return 100;
582}
583
584let buffer: ArrayBuffer = new ArrayBuffer(8);
585let view: Uint8Array = new Uint8Array(buffer);
586let buffer1: ArrayBuffer = new ArrayBuffer(16);
587let view1: Uint8Array = new Uint8Array(buffer1);
588
589console.info("testTransfer view byteLength: " + view.byteLength);
590console.info("testTransfer view1 byteLength: " + view1.byteLength);
591
592let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1);
593task.setTransferList([view.buffer, view1.buffer]);
594taskpool.execute(task).then((res: Object)=>{
595  console.info("test result: " + res);
596}).catch((e: string)=>{
597  console.error("test catch: " + e);
598})
599console.info("testTransfer view byteLength: " + view.byteLength);
600console.info("testTransfer view1 byteLength: " + view1.byteLength);
601```
602
603
604### setCloneList<sup>11+</sup>
605
606setCloneList(cloneList: Object[] | ArrayBuffer[]): void
607
608Sets the task clone list. Before using this API, you must create a **Task** instance.
609
610> **NOTE**<br>
611> Currently, only clone is supported. This API must be used together with [@Sendable decorator](../../arkts-utils/arkts-sendable.md). Otherwise, an exception is thrown.
612
613**System capability**: SystemCapability.Utils.Lang
614
615**Parameters**
616
617| Name   | Type                     | Mandatory| Description                                         |
618| --------- | ------------------------ | ---- | --------------------------------------------- |
619| cloneList | Object[] \| ArrayBuffer[]  | Yes| - The type of the passed-in array must be [SendableClass](../../arkts-utils/arkts-sendable.md#basic-concepts) or ArrayBuffer.<br>- For **SendableClass** instances or **ArrayBuffer** objects held by all objects passed in to the clone list, the inter-thread transmission behavior changes to the clone operation. This means that any modification to the transmitted objects does not affect the original objects.|
620
621**Error codes**
622
623For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
624
625| ID| Error Message                                                       |
626| -------- | -------------------------------------------------------------- |
627| 10200029 | Can not set an arraybuffer to both transferList and cloneList. |
628
629**Example**
630
631```ts
632import taskpool from '@ohos.taskpool'
633import { BusinessError } from '@ohos.base'
634
635@Sendable
636class BaseClass {
637  private str: string = "sendable: BaseClass";
638  static num :number = 10;
639  str1: string = "sendable: this is BaseClass's string";
640  num1: number = 5;
641  isDone1: boolean = false;
642
643  private fibonacciRecursive(n: number): number {
644    if (n <= 1) {
645      return n;
646    } else {
647      return this.fibonacciRecursive(n - 1) + this.fibonacciRecursive(n - 2);
648    }
649  }
650
651  private privateFunc(num: number): number{
652    let res: number = this.fibonacciRecursive(num);
653    console.info("sendable: BaseClass privateFunc res is: " + res);
654    return res;
655  }
656
657  publicFunc(num: number): number {
658    return this.privateFunc(num);
659  }
660
661  get GetNum(): number {
662    return this.num1;
663  }
664  set SetNum(num: number) {
665    this.num1 = num;
666  }
667
668  constructor(){
669    console.info(this.str);
670    this.isDone1 = true;
671  }
672}
673
674@Sendable
675class DeriveClass extends BaseClass {
676  name: string = "sendable: this is DeriveClass";
677  printName() {
678    console.info(this.name);
679  }
680  constructor() {
681    super();
682  }
683}
684
685@Concurrent
686function testFunc(arr: Array<BaseClass>, num: number): number {
687  let baseInstance1 = arr[0];
688  console.info("sendable: str1 is: " + baseInstance1.str1);
689  baseInstance1.SetNum = 100;
690  console.info("sendable: num1 is: " + baseInstance1.GetNum);
691  console.info("sendable: isDone1 is: " + baseInstance1.isDone1);
692  // Obtain the result of the item specified by num from Fibonacci sequence.
693  let res: number = baseInstance1.publicFunc(num);
694  return res;
695}
696
697@Concurrent
698function printLog(arr: Array<DeriveClass>): void {
699  let deriveInstance = arr[0];
700  deriveInstance.printName();
701}
702
703@Entry
704@Component
705struct Index {
706  @State message: string = 'Hello World'
707
708  build() {
709    Row() {
710      Column() {
711        Text(this.message)
712          .fontSize(50)
713          .fontWeight(FontWeight.Bold)
714        Button() {
715          Text("TaskPool Test")
716        }.onClick(() => {
717          // task1 calls BaseClass.str1/BaseClass.SetNum/BaseClass.GetNum/BaseClass.isDone1/BaseClass.publicFunc.
718          let baseInstance1: BaseClass = new BaseClass();
719          let array1 = new Array<BaseClass>();
720          array1.push(baseInstance1);
721          let task1 = new taskpool.Task(testFunc, array1, 10);
722          task1.setCloneList(array1);
723          taskpool.execute(task1).then((res: Object) => {
724            console.info("sendable: task1 res is: " + res);
725          }).catch((e:BusinessError) => {
726            console.error(`sendable: task1 execute Code is ${e.code}, message is ${e.message}`);
727          })
728
729          // task2 calls DeriveClass.printName.
730          let deriveInstance: DeriveClass = new DeriveClass();
731          let array2 = new Array<DeriveClass>();
732          array2.push(deriveInstance);
733          let task2 = new taskpool.Task(printLog, array2);
734          task2.setCloneList(array2);
735          taskpool.execute(task2).then(() => {
736            console.info("sendable: task2 execute success");
737          }).catch((e:BusinessError) => {
738            console.error(`sendable: task2 execute Code is ${e.code}, message is ${e.message}`);
739          })
740        })
741        .height('15%')
742        .width('30%')
743      }
744      .width('100%')
745    }
746    .height('100%')
747  }
748}
749```
750
751
752### sendData<sup>11+</sup>
753
754static sendData(...args: Object[]): void
755
756Sends data to the host thread and triggers the registered callback. Before using this API, you must create a **Task** instance.
757
758**System capability**: SystemCapability.Utils.Lang
759
760**Parameters**
761
762| Name  | Type         | Mandatory| Description                                             |
763| -------- | ------------- | ---- | ------------------------------------------------- |
764| args     | Object[]      | Yes  | Data to be used as the input parameter of the registered callback. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
765
766**Error codes**
767
768For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
769
770| ID| Error Message                                |
771| -------- | --------------------------------------- |
772| 10200006  | An exception occurred during serialization. |
773| 10200022  | The function is not called in the taskpool thread. |
774| 10200023  | The function is not called in the concurrent function. |
775| 10200024  | The callback is not registered on the host side. |
776
777**Example**
778
779```ts
780@Concurrent
781function ConcurrentFunc(num: number): number {
782  let res: number = num * 10;
783  taskpool.Task.sendData(res);
784  return num;
785}
786```
787
788### onReceiveData<sup>11+</sup>
789
790onReceiveData(callback?: Function): void
791
792Registers a callback for a task to receive and process data from the worker thread. Before using this API, you must create a **Task** instance.
793
794> **NOTE**<br>
795> If multiple callbacks are registered for the same task, only the last registration takes effect.
796
797**System capability**: SystemCapability.Utils.Lang
798
799**Parameters**
800
801| Name  | Type    | Mandatory| Description                                                        |
802| -------- | -------- | ---- | ------------------------------------------------------------ |
803| callback | Function | No  | Callback function for processing the data received. The data sent to the host thread is transferred to the callback as an input parameter. If no value is passed in, all the registered callbacks are canceled.|
804
805**Example**
806
807```ts
808@Concurrent
809function ConcurrentFunc(num: number): number {
810  let res: number = num * 10;
811  taskpool.Task.sendData(res);
812  return num;
813}
814
815function pringLog(data: number): void {
816  console.info("taskpool: data is: " + data);
817}
818
819async function testFunc(): Promise<void> {
820  try {
821    let task: taskpool.Task = new taskpool.Task(ConcurrentFunc, 1);
822    task.onReceiveData(pringLog);
823    await taskpool.execute(task);
824  } catch (e) {
825    console.info(`taskpool: error code: ${e.code}, info: ${e.message}`);
826  }
827}
828
829testFunc();
830```
831
832### addDependency<sup>11+</sup>
833
834addDependency(...tasks: Task[]): void
835
836Adds dependent tasks for this task. Before using this API, you must create a **Task** instance. The task cannot be a task in a task group or queue, or a task that has been executed.
837
838**System capability**: SystemCapability.Utils.Lang
839
840**Parameters**
841
842| Name| Type  | Mandatory| Description              |
843| ------ | ------ | ---- | ------------------ |
844| tasks  | [Task](#task)[] | Yes  | Array of tasks on which the current task depends.|
845
846**Error codes**
847
848For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
849
850| ID| Error Message                       |
851| -------- | ------------------------------- |
852| 10200026 | There is a circular dependency. |
853
854**Example**
855
856```ts
857@Concurrent
858function delay(args: number): number {
859  let t: number = Date.now();
860  while ((Date.now() - t) < 1000) {
861	continue;
862  }
863  return args;
864}
865
866let task1:taskpool.Task = new taskpool.Task(delay, 100);
867let task2:taskpool.Task = new taskpool.Task(delay, 200);
868let task3:taskpool.Task = new taskpool.Task(delay, 200);
869
870console.info("dependency: add dependency start");
871task1.addDependency(task2);
872task2.addDependency(task3);
873console.info("dependency: add dependency end");
874
875console.info("dependency: start execute second")
876taskpool.execute(task1).then(() => {
877  console.info("dependency: second task1 success");
878})
879taskpool.execute(task2).then(() => {
880  console.info("dependency: second task2 success");
881})
882taskpool.execute(task3).then(() => {
883  console.info("dependency: second task3 success");
884})
885```
886
887### removeDependency<sup>11+</sup>
888
889removeDependency(...tasks: Task[]): void
890
891Removes dependent tasks for this task. Before using this API, you must create a **Task** instance.
892
893**System capability**: SystemCapability.Utils.Lang
894
895**Parameters**
896
897| Name| Type  | Mandatory| Description              |
898| ------ | ------ | ---- | ------------------ |
899| tasks  | [Task](#task)[] | Yes  | Array of tasks on which the current task depends.|
900
901**Error codes**
902
903For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
904
905| ID| Error Message                      |
906| -------- | ------------------------------ |
907| 10200027 | The dependency does not exist. |
908
909**Example**
910
911```ts
912@Concurrent
913function delay(args: number): number {
914  let t: number = Date.now();
915  while ((Date.now() - t) < 1000) {
916	continue;
917  }
918  return args;
919}
920
921let task1:taskpool.Task = new taskpool.Task(delay, 100);
922let task2:taskpool.Task = new taskpool.Task(delay, 200);
923let task3:taskpool.Task = new taskpool.Task(delay, 200);
924
925console.info("dependency: add dependency start");
926task1.addDependency(task2);
927task2.addDependency(task3);
928console.info("dependency: add dependency end");
929console.info("dependency: remove dependency start");
930task1.removeDependency(task2);
931task2.removeDependency(task3);
932console.info("dependency: remove dependency end");
933
934console.info("dependency: start execute")
935taskpool.execute(task1).then(() => {
936  console.info("dependency: task1 success");
937})
938taskpool.execute(task2).then(() => {
939  console.info("dependency: task2 success");
940})
941taskpool.execute(task3).then(() => {
942  console.info("dependency: task3 success");
943})
944```
945
946### Attributes
947
948**System capability**: SystemCapability.Utils.Lang
949
950| Name                | Type      | Readable| Writable| Description                                                        |
951| -------------------- | --------- | ---- | ---- | ------------------------------------------------------------ |
952| function             | Function  | Yes  | Yes  | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).|
953| arguments            | Object[]  | Yes  | Yes  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
954| name<sup>11+</sup>   | string    | Yes  | Yes  | Name of the task specified when the task is created.                                   |
955| totalDuration<sup>11+</sup>  | number    | Yes  | No  | Total execution time of the task.                                   |
956| ioDuration<sup>11+</sup>     | number    | Yes  | No  | Asynchronous I/O time of the task.                                   |
957| cpuDuration<sup>11+</sup>    | number    | Yes  | No  | CPU time of the task.                                   |
958
959## TaskGroup<sup>10+</sup>
960
961Implements a task group, in which all tasks are executed at a time. If all the tasks are executed normally, an array of task results is returned asynchronously, and the sequence of elements in the array is the same as the sequence of tasks added by calling [addTask](#addtask10-1). If any task fails, the corresponding exception is thrown. A task group can be executed for multiple times, but no task can be added after the task group is executed. Before calling any APIs in **TaskGroup**, you must use [constructor](#constructor10) to create a **TaskGroup** instance.
962
963### constructor<sup>10+</sup>
964
965constructor()
966
967Constructor used to create a **TaskGroup** instance.
968
969**System capability**: SystemCapability.Utils.Lang
970
971**Example**
972
973```ts
974let taskGroup = new taskpool.TaskGroup();
975```
976
977### constructor<sup>11+</sup>
978
979constructor(name: string)
980
981A constructor used to create a **TaskGroup** instance, with the task group name specified.
982
983**System capability**: SystemCapability.Utils.Lang
984
985**Parameters**
986
987| Name| Type  | Mandatory| Description        |
988| ------ | ------ | ---- | ------------ |
989| name   | string | Yes  | Task group name.|
990
991**Example**
992
993```ts
994let taskGroupName: string = "groupName";
995let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(taskGroupName);
996let name: string = taskGroup.name;
997```
998
999### addTask<sup>10+</sup>
1000
1001addTask(func: Function, ...args: Object[]): void
1002
1003Adds the function to be executed to this task group. Before using this API, you must create a **TaskGroup** instance. Tasks in another task group or queue, dependent tasks, and tasks that have been executed cannot be added to the task group.
1004
1005**System capability**: SystemCapability.Utils.Lang
1006
1007**Parameters**
1008
1009| Name| Type     | Mandatory| Description                                                                  |
1010| ------ | --------- | ---- | ---------------------------------------------------------------------- |
1011| func   | Function  | Yes  | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
1012| args   | Object[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
1013
1014**Error codes**
1015
1016For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
1017
1018| ID| Error Message                                |
1019| -------- | --------------------------------------- |
1020| 10200014 | The function is not mark as concurrent. |
1021
1022**Example**
1023
1024```ts
1025@Concurrent
1026function printArgs(args: number): number {
1027  console.info("printArgs: " + args);
1028  return args;
1029}
1030
1031let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
1032taskGroup.addTask(printArgs, 100); // 100: test number
1033```
1034
1035### addTask<sup>10+</sup>
1036
1037addTask(task: Task): void
1038
1039Adds a created task to this task group. Before using this API, you must create a **TaskGroup** instance.
1040
1041**System capability**: SystemCapability.Utils.Lang
1042
1043**Parameters**
1044
1045| Name  | Type                 | Mandatory| Description                                      |
1046| -------- | --------------------- | ---- | ---------------------------------------- |
1047| task     | [Task](#task)         | Yes  | Task to be added to the task group.                 |
1048
1049**Error codes**
1050
1051For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
1052
1053| ID| Error Message                                |
1054| -------- | --------------------------------------- |
1055| 10200014 | The function is not mark as concurrent. |
1056
1057**Example**
1058
1059```ts
1060@Concurrent
1061function printArgs(args: number): number {
1062  console.info("printArgs: " + args);
1063  return args;
1064}
1065
1066let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
1067let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
1068taskGroup.addTask(task);
1069```
1070
1071### Attributes
1072
1073**System capability**: SystemCapability.Utils.Lang
1074
1075| Name| Type  | Readable| Writable| Description                        |
1076| ---- | ------ | ---- | ---- | ---------------------------- |
1077| name<sup>11+</sup> | string | Yes  | Yes  | Name of the task group specified when the task group is created.|
1078
1079## SequenceRunner <sup>11+</sup>
1080
1081Implements a queue that executes the tasks in sequence. Before calling any APIs in **SequenceRunner**, you must use [constructor](#constructor11-3) to create a **SequenceRunner** instance.
1082
1083### constructor<sup>11+</sup>
1084
1085constructor(priority?: Priority)
1086
1087A constructor used to create a **SequenceRunner** instance.
1088
1089**System capability**: SystemCapability.Utils.Lang
1090
1091**Parameters**
1092
1093| Name  | Type                 | Mandatory| Description                                                      |
1094| -------- | --------------------- | ---- | ---------------------------------------------------------- |
1095| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
1096
1097**Example**
1098
1099```ts
1100let runner: taskpool.SequenceRunner = new taskpool.SequenceRunner();
1101```
1102
1103### execute<sup>11+</sup>
1104
1105execute(task: Task): Promise\<Object>
1106
1107Adds a task to the queue for execution. Before using this API, you must create a **SequenceRunner** instance. Tasks in another task group or queue, dependent tasks, and tasks that have been executed cannot be added to the queue.
1108
1109> **NOTE**
1110>
1111> - Tasks that depend others cannot be added to the queue.
1112> - The failure or cancellation of a task does not affect the execution of subsequent tasks in the queue.
1113
1114**System capability**: SystemCapability.Utils.Lang
1115
1116**Parameters**
1117
1118| Name| Type         | Mandatory| Description                            |
1119| ------ | ------------- | ---- | -------------------------------- |
1120| task   | [Task](#task) | Yes  | Task to be added to the queue.|
1121
1122**Return value**
1123
1124| Type            | Description                             |
1125| ---------------- | --------------------------------- |
1126| Promise\<Object> | Promise used to return the task execution result.|
1127
1128**Error codes**
1129
1130For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
1131
1132| ID| Error Message                                   |
1133| -------- | ------------------------------------------- |
1134| 10200003 | Worker initialization failure.              |
1135| 10200006 | An exception occurred during serialization. |
1136| 10200025 | Add dependent task to SequenceRunner.       |
1137
1138**Example**
1139
1140```ts
1141@Concurrent
1142function additionDelay(delay:number): void {
1143  let start: number = new Date().getTime();
1144  while (new Date().getTime() - start < delay) {
1145    continue;
1146  }
1147}
1148@Concurrent
1149function waitForRunner(finalString: string): string {
1150  return finalString;
1151}
1152async function seqRunner()
1153{
1154  let finalString:string = "";
1155  let task1:taskpool.Task = new taskpool.Task(additionDelay, 3000);
1156  let task2:taskpool.Task = new taskpool.Task(additionDelay, 2000);
1157  let task3:taskpool.Task = new taskpool.Task(additionDelay, 1000);
1158  let task4:taskpool.Task = new taskpool.Task(waitForRunner, finalString);
1159
1160  let runner:taskpool.SequenceRunner = new taskpool.SequenceRunner();
1161  runner.execute(task1).then(() => {
1162    finalString += 'a';
1163    console.info("seqrunner: task1 done.");
1164  });
1165  runner.execute(task2).then(() => {
1166    finalString += 'b';
1167    console.info("seqrunner: task2 done");
1168  });
1169  runner.execute(task3).then(() => {
1170    finalString += 'c';
1171    console.info("seqrunner: task3 done");
1172  });
1173  await runner.execute(task4);
1174  console.info("seqrunner: task4 done, finalString is " + finalString);
1175}
1176```
1177
1178## State<sup>10+</sup>
1179
1180Enumerates the task states.
1181
1182**System capability**: SystemCapability.Utils.Lang
1183
1184| Name     | Value       | Description         |
1185| --------- | -------- | ------------- |
1186| WAITING   | 1        | The task is waiting.|
1187| RUNNING   | 2        | The task is running.|
1188| CANCELED  | 3        | The task is canceled.|
1189
1190
1191## TaskInfo<sup>10+</sup>
1192
1193Describes the internal information about a task.
1194
1195**System capability**: SystemCapability.Utils.Lang
1196
1197### Attributes
1198
1199**System capability**: SystemCapability.Utils.Lang
1200
1201| Name    | Type               | Readable| Writable| Description                                                          |
1202| -------- | ------------------ | ---- | ---- | ------------------------------------------------------------- |
1203| taskId   | number             | Yes  | No  | Task ID.                                                    |
1204| state    | [State](#state10)  | Yes  | No  | Task state.                                                   |
1205| duration | number             | Yes  | No  | Duration that the task has been executed, in ms. If the return value is **0**, the task is not running. If the return value is empty, no task is running. |
1206
1207## ThreadInfo<sup>10+</sup>
1208
1209Describes the internal information about a worker thread.
1210
1211**System capability**: SystemCapability.Utils.Lang
1212
1213### Attributes
1214
1215**System capability**: SystemCapability.Utils.Lang
1216
1217| Name    | Type                   | Readable| Writable| Description                                                     |
1218| -------- | ---------------------- | ---- | ---- | -------------------------------------------------------- |
1219| tid      | number                 | Yes  | No  | ID of the worker thread. If the return value is empty, no task is running.             |
1220| taskIds  | number[]               | Yes  | No  | IDs of tasks running on the calling thread. If the return value is empty, no task is running.  |
1221| priority | [Priority](#priority)  | Yes  | No  | Priority of the calling thread. If the return value is empty, no task is running.             |
1222
1223## TaskPoolInfo<sup>10+</sup>
1224
1225Describes the internal information about a task pool.
1226
1227**System capability**: SystemCapability.Utils.Lang
1228
1229### Attributes
1230
1231**System capability**: SystemCapability.Utils.Lang
1232
1233| Name         | Type                             | Readable| Writable| Description                 |
1234| ------------- | -------------------------------- | ---- | ---- | -------------------- |
1235| threadInfos   | [ThreadInfo[]](#threadinfo10)    | Yes  | No  | Internal information about the worker threads.  |
1236| taskInfos     | [TaskInfo[]](#taskinfo10)        | Yes  | No  | Internal information about the tasks.      |
1237
1238
1239## Additional Information
1240
1241### Sequenceable Data Types
1242The following sequenceable data types are supported: All Primitive Type (excluding symbol), Date, String, RegExp, Array, Map, Set, Object, ArrayBuffer, and TypedArray.
1243
1244### Using the Task Pool in Simple Mode
1245
1246**Example 1**
1247
1248```ts
1249// Common functions are supported, and variables passed in by input parameters are also supported.
1250@Concurrent
1251function printArgs(args: number): number {
1252  console.info("func: " + args);
1253  return args;
1254}
1255async function taskpoolExecute(): Promise<void> {
1256  // taskpool.execute(task)
1257  let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
1258  console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
1259  // taskpool.execute(function)
1260  console.info("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
1261}
1262taskpoolExecute();
1263```
1264
1265**Example 2**
1266
1267```ts
1268// b.ets
1269export let c: string = "hello";
1270```
1271```ts
1272// Reference an imported variable.
1273// a.ets (in the same directory as b.ets)
1274import { c } from "./b";
1275
1276@Concurrent
1277function printArgs(a: string): string {
1278    console.info(a);
1279    console.info(c);
1280    return a;
1281}
1282
1283async function taskpoolExecute(): Promise<void> {
1284  // taskpool.execute(task)
1285  let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
1286  console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
1287
1288  // taskpool.execute(function)
1289  console.info("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
1290}
1291
1292taskpoolExecute();
1293```
1294
1295**Example 3**
1296
1297```ts
1298// The async functions are supported.
1299@Concurrent
1300async function delayExcute(): Promise<Object> {
1301  let ret = await Promise.all<Object>([
1302    new Promise<Object>(resolve => setTimeout(resolve, 1000, "resolved"))
1303  ]);
1304  return ret;
1305}
1306
1307async function taskpoolExecute(): Promise<void> {
1308  taskpool.execute(delayExcute).then((result: Object) => {
1309    console.info("taskPoolTest task result: " + result);
1310  }).catch((err: string) => {
1311    console.error("taskpool test occur error: " + err);
1312  });
1313}
1314
1315taskpoolExecute();
1316```
1317
1318**Example 4**
1319
1320```ts
1321// c.ets
1322import taskpool from '@ohos.taskpool';
1323
1324@Concurrent
1325function strSort(inPutArr: Array<string>): Array<string> {
1326  let newArr = inPutArr.sort();
1327  return newArr;
1328}
1329export async function func1(): Promise<void> {
1330  console.info("taskpoolTest start");
1331  let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
1332  let task: taskpool.Task = new taskpool.Task(strSort, strArray);
1333  console.info("func1 result:" + await taskpool.execute(task));
1334}
1335
1336export async function func2(): Promise<void> {
1337  console.info("taskpoolTest2 start");
1338  let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
1339  taskpool.execute(strSort, strArray).then((result: Object) => {
1340    console.info("func2 result: " + result);
1341  }).catch((err: string) => {
1342    console.error("taskpool test occur error: " + err);
1343  });
1344}
1345```
1346
1347```ts
1348// index.ets
1349import { func1, func2 } from "./c";
1350
1351func1();
1352func2();
1353```
1354
1355**Example 5**
1356
1357```ts
1358// Success in canceling a task
1359@Concurrent
1360function inspectStatus(arg: number): number {
1361  // Check whether the task has been canceled and respond accordingly.
1362  if (taskpool.Task.isCanceled()) {
1363    console.info("task has been canceled before 2s sleep.");
1364    return arg + 2;
1365  }
1366  // 2s sleep
1367  let t: number = Date.now();
1368  while (Date.now() - t < 2000) {
1369    continue;
1370  }
1371  // Check again whether the task has been canceled and respond accordingly.
1372  if (taskpool.Task.isCanceled()) {
1373    console.info("task has been canceled after 2s sleep.");
1374    return arg + 3;
1375  }
1376  return arg + 1;
1377}
1378
1379async function taskpoolCancel(): Promise<void> {
1380  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
1381  taskpool.execute(task).then((res: Object)=>{
1382    console.info("taskpool test result: " + res);
1383  }).catch((err: string) => {
1384    console.error("taskpool test occur error: " + err);
1385  });
1386  // Cancel the task 1s later.
1387  setTimeout(()=>{
1388    taskpool.cancel(task);}, 1000);
1389}
1390
1391taskpoolCancel();
1392```
1393
1394**Example 6**
1395
1396```ts
1397// Failure to cancel a task that has been executed
1398@Concurrent
1399function inspectStatus(arg: number): number {
1400  // Check whether the task has been canceled and respond accordingly.
1401  if (taskpool.Task.isCanceled()) {
1402    return arg + 2;
1403  }
1404  // Wait for 2s.
1405  let t: number = Date.now();
1406  while (Date.now() - t < 500) {
1407    continue;
1408  }
1409  // Check again whether the task has been canceled and respond accordingly.
1410  if (taskpool.Task.isCanceled()) {
1411    return arg + 3;
1412  }
1413  return arg + 1;
1414}
1415
1416async function taskpoolCancel(): Promise<void> {
1417  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
1418  taskpool.execute(task).then((res: Object)=>{
1419    console.info("taskpool test result: " + res);
1420  }).catch((err: string) => {
1421    console.error("taskpool test occur error: " + err);
1422  });
1423
1424  setTimeout(()=>{
1425    try {
1426      taskpool.cancel(task); // The task has been executed and fails to be canceled.
1427    } catch (e) {
1428      console.error("taskpool.cancel occur error:" + e);
1429    }
1430  }, 3000); // Wait for 3s to ensure that the task has been executed.
1431}
1432
1433taskpoolCancel();
1434```
1435
1436**Example 7**
1437
1438```ts
1439// Success of canceling a task group to be executed
1440@Concurrent
1441function printArgs(args: number): number {
1442  let t: number = Date.now();
1443  while (Date.now() - t < 1000) {
1444    continue;
1445  }
1446  console.info("printArgs: " + args);
1447  return args;
1448}
1449
1450async function taskpoolGroupCancelTest(): Promise<void> {
1451  let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
1452  taskGroup1.addTask(printArgs, 10); // 10: test number
1453  taskGroup1.addTask(printArgs, 20); // 20: test number
1454  taskGroup1.addTask(printArgs, 30); // 30: test number
1455  let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
1456  let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
1457  let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
1458  let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
1459  taskGroup2.addTask(task1);
1460  taskGroup2.addTask(task2);
1461  taskGroup2.addTask(task3);
1462  taskpool.execute(taskGroup1).then((res: Array<Object>) => {
1463    console.info("taskpool execute res is:" + res);
1464  }).catch((e: string) => {
1465    console.error("taskpool execute error is:" + e);
1466  });
1467  taskpool.execute(taskGroup2).then((res: Array<Object>) => {
1468    console.info("taskpool execute res is:" + res);
1469  }).catch((e: string) => {
1470    console.error("taskpool execute error is:" + e);
1471  });
1472
1473  taskpool.cancel(taskGroup2);
1474}
1475
1476taskpoolGroupCancelTest()
1477```
1478
1479**Example 8**
1480
1481```ts
1482// Create and execute 100 tasks with different priorities, and view their information.
1483@Concurrent
1484function delay(): void {
1485  let start: number = new Date().getTime();
1486  while (new Date().getTime() - start < 500) {
1487    continue;
1488  }
1489}
1490
1491let highCount: number = 0;
1492let mediumCount: number = 0;
1493let lowCount: number = 0;
1494let allCount: number = 100;
1495for (let i = 0; i < allCount; i++) {
1496  let task1: taskpool.Task = new taskpool.Task(delay);
1497  let task2: taskpool.Task = new taskpool.Task(delay);
1498  let task3: taskpool.Task = new taskpool.Task(delay);
1499  taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
1500    lowCount++;
1501  }).catch((e: string) => {
1502    console.error("low task error: " + e);
1503  })
1504  taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
1505    mediumCount++;
1506  }).catch((e: string) => {
1507    console.error("medium task error: " + e);
1508  })
1509  taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
1510    highCount++;
1511  }).catch((e: string) => {
1512    console.error("high task error: " + e);
1513  })
1514}
1515let start: number = new Date().getTime();
1516while (new Date().getTime() - start < 1000) {
1517  continue;
1518}
1519let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
1520let tid: number = 0;
1521let taskIds: Array<number> = [];
1522let priority: number = 0;
1523let taskId: number = 0;
1524let state: number = 0;
1525let duration: number = 0;
1526let threadIS = Array.from(taskpoolInfo.threadInfos)
1527for(let threadInfo of threadIS) {
1528  tid = threadInfo.tid;
1529  if (threadInfo.taskIds != undefined && threadInfo.priority != undefined )
1530  {
1531    taskIds.length = threadInfo.taskIds.length;
1532    priority = threadInfo.priority;
1533  }
1534  console.info("taskpool---tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority);
1535}
1536let taskIS = Array.from(taskpoolInfo.taskInfos)
1537for(let taskInfo of taskIS) {
1538  taskId = taskInfo.taskId;
1539  state = taskInfo.state;
1540  if (taskInfo.duration != undefined )
1541  {
1542    duration = taskInfo.duration;
1543  }
1544  console.info("taskpool---taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration);
1545}
1546```
1547