• 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
11> **NOTE**<br>
12> 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.
13
14## Modules to Import
15
16```ts
17import taskpool from '@ohos.taskpool';
18```
19## taskpool.execute
20
21execute(func: Function, ...args: unknown[]): Promise\<unknown>
22
23Places the function to be executed in the internal task 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.
24
25**System capability**: SystemCapability.Utils.Lang
26
27**Parameters**
28
29| Name| Type     | Mandatory| Description                                                                  |
30| ------ | --------- | ---- | ---------------------------------------------------------------------- |
31| 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).    |
32| args   | unknown[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
33
34**Return value**
35
36| Type             | Description                                |
37| ----------------- | ------------------------------------ |
38| Promise\<unknown> | Promise used to return the result.|
39
40**Error codes**
41
42For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
43
44| ID| Error Message                                     |
45| -------- | -------------------------------------------- |
46| 10200003 | Worker initialization failure.               |
47| 10200006 | An exception occurred during serialization.  |
48| 10200014 | The function is not mark as concurrent.      |
49
50**Example**
51
52```ts
53@Concurrent
54function printArgs(args: number): number {
55    console.log("printArgs: " + args);
56    return args;
57}
58
59taskpool.execute(printArgs, 100).then((value: number) => { // 100: test number
60  console.log("taskpool result: " + value);
61});
62```
63
64## taskpool.execute
65
66execute(task: Task, priority?: Priority): Promise\<unknown>
67
68Places a task in the internal task 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.
69
70**System capability**: SystemCapability.Utils.Lang
71
72**Parameters**
73
74| Name  | Type                 | Mandatory| Description                                      |
75| -------- | --------------------- | ---- | ---------------------------------------- |
76| task     | [Task](#task)         | Yes  | Task to be executed.                 |
77| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
78
79**Return value**
80
81| Type             | Description             |
82| ----------------  | ---------------- |
83| Promise\<unknown> | Promise used to return the result.|
84
85**Error codes**
86
87For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
88
89| ID| Error Message                                    |
90| -------- | ------------------------------------------- |
91| 10200003 | Worker initialization failure.              |
92| 10200006 | An exception occurred during serialization. |
93| 10200014 | The function is not mark as concurrent.     |
94
95**Example**
96
97```ts
98@Concurrent
99function printArgs(args: number): number {
100    console.log("printArgs: " + args);
101    return args;
102}
103
104let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
105taskpool.execute(task).then((value: number) => {
106  console.log("taskpool result: " + value);
107});
108```
109
110## taskpool.execute<sup>10+</sup>
111
112execute(group: TaskGroup, priority?: Priority): Promise<unknown[]>
113
114Places a task group in the internal task queue of the task pool. The task group will be distributed to the worker thread for execution.
115
116**System capability**: SystemCapability.Utils.Lang
117
118**Parameters**
119
120| Name    | Type                       | Mandatory| Description                                                          |
121| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
122| group     | [TaskGroup](#taskgroup)     | Yes  | Task group to be executed.                                     |
123| priority  | [Priority](#priority)       | No  | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.|
124
125**Return value**
126
127| Type                | Description                              |
128| ----------------    | ---------------------------------- |
129| Promise\<unknown[]> | Promise used to return the result.|
130
131**Error codes**
132
133For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
134
135| ID| Error Message                                    |
136| -------- | ------------------------------------------- |
137| 10200006 | An exception occurred during serialization. |
138
139**Example**
140
141```ts
142@Concurrent
143function printArgs(args: number): number {
144    console.log("printArgs: " + args);
145    return args;
146}
147
148let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
149taskGroup1.addTask(printArgs, 10); // 10: test number
150taskGroup1.addTask(printArgs, 20); // 20: test number
151taskGroup1.addTask(printArgs, 30); // 30: test number
152
153let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
154let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
155let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
156let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
157taskGroup2.addTask(task1);
158taskGroup2.addTask(task2);
159taskGroup2.addTask(task3);
160taskpool.execute(taskGroup1).then((res: Array<number>) => {
161  console.info("taskpool execute res is:" + res);
162});
163taskpool.execute(taskGroup2).then((res: Array<number>) => {
164  console.info("taskpool execute res is:" + res);
165});
166```
167
168## taskpool.cancel
169
170cancel(task: Task): void
171
172Cancels a task in the task pool.
173
174**System capability**: SystemCapability.Utils.Lang
175
176**Parameters**
177
178| Name| Type         | Mandatory| Description                |
179| ------ | ------------- | ---- | -------------------- |
180| task   | [Task](#task) | Yes  | Task to cancel.|
181
182**Error codes**
183
184For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
185
186| ID| Error Message                                     |
187| -------- | -------------------------------------------- |
188| 10200015 | The task does not exist when it is canceled. |
189| 10200016 | The task is executing when it is canceled.   |
190
191Since API version 10, error code 10200016 is not reported when this API is called.
192
193**Example of canceling an ongoing task**
194
195```ts
196@Concurrent
197function inspectStatus(arg: number): number {
198  // Check the cancellation status and return the result.
199  if (taskpool.Task.isCanceled()) {
200    console.log("task has been canceled before 2s sleep.");
201    return arg + 2;
202  }
203  // 2s sleep
204  let t: number = Date.now();
205  while (Date.now() - t < 2000) {
206    continue;
207  }
208  // Check the cancellation status again and return the result.
209  if (taskpool.Task.isCanceled()) {
210    console.log("task has been canceled after 2s sleep.");
211    return arg + 3;
212  }
213  return arg + 1;
214}
215
216let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
217let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number
218let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number
219let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number
220let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number
221let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number
222taskpool.execute(task1).then((res: number)=>{
223  console.log("taskpool test result: " + res);
224});
225taskpool.execute(task2);
226taskpool.execute(task3);
227taskpool.execute(task4);
228taskpool.execute(task5);
229taskpool.execute(task6);
230// Cancel the task 1s later.
231setTimeout(()=>{
232  taskpool.cancel(task1);}, 1000);
233```
234
235## taskpool.cancel<sup>10+</sup>
236
237cancel(group: TaskGroup): void
238
239Cancels a task group in the task pool.
240
241**System capability**: SystemCapability.Utils.Lang
242
243**Parameters**
244
245| Name  | Type                   | Mandatory| Description                |
246| ------- | ----------------------- | ---- | -------------------- |
247| group   | [TaskGroup](#taskgroup) | Yes  | Task group to cancel.|
248
249**Error codes**
250
251For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
252
253| ID| Error Message                                                |
254| -------- | ------------------------------------------------------- |
255| 10200018 | The task group does not exist when it is canceled.      |
256
257**Example**
258
259```ts
260@Concurrent
261function printArgs(args: number): number {
262  let t: number = Date.now();
263  while (Date.now() - t < 2000) {
264    continue;
265  }
266  console.log("printArgs: " + args);
267  return args;
268}
269
270let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
271taskGroup1.addTask(printArgs, 10); // 10: test number
272let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
273taskGroup2.addTask(printArgs, 100); // 100: test number
274taskpool.execute(taskGroup1).then((res: Array<number>)=>{
275  console.info("taskGroup1 res is:" + res)
276});
277taskpool.execute(taskGroup2).then((res: Array<number>)=>{
278  console.info("taskGroup2 res is:" + res)
279});
280setTimeout(()=>{
281  try {
282    taskpool.cancel(taskGroup2);
283  } catch (e) {
284    console.log("taskGroup.cancel occur error:" + e);
285  }
286}, 1000);
287```
288
289
290## taskpool.getTaskPoolInfo<sup>10+</sup>
291
292getTaskPoolInfo(): TaskPoolInfo
293
294Obtains the internal information about this task pool.
295
296**System capability**: SystemCapability.Utils.Lang
297
298**Return value**
299
300| Type                               | Description               |
301| ----------------------------------- | ------------------ |
302| [TaskPoolInfo](#taskpoolinfo10)   | Internal information about the task pool.  |
303
304**Example**
305
306```ts
307let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
308```
309
310## Priority
311
312Enumerates the priorities available for created tasks.
313
314**System capability**: SystemCapability.Utils.Lang
315
316| Name| Value| Description|
317| -------- | -------- | -------- |
318| HIGH   | 0    | The task has a high priority.|
319| MEDIUM | 1 | The task has a medium priority.|
320| LOW | 2 | The task has a low priority.|
321
322**Example**
323
324```ts
325@Concurrent
326function printArgs(args: number): number {
327  console.log("printArgs: " + args);
328  return args;
329}
330
331let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
332let highCount = 0;
333let mediumCount = 0;
334let lowCount = 0;
335let allCount = 100;
336for (let i: number = 0; i < allCount; i++) {
337  taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => {
338    lowCount++;
339    console.log("taskpool lowCount is :" + lowCount);
340  });
341  taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => {
342    mediumCount++;
343    console.log("taskpool mediumCount is :" + mediumCount);
344  });
345  taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => {
346    highCount++;
347    console.log("taskpool highCount is :" + highCount);
348  });
349}
350```
351
352## Task
353
354Implements a task. Before calling any APIs in **Task**, you must use [constructor](#constructor) to create a **Task** instance.
355
356### constructor
357
358constructor(func: Function, ...args: unknown[])
359
360A constructor used to create a **Task** instance.
361
362**System capability**: SystemCapability.Utils.Lang
363
364**Parameters**
365
366| Name| Type     | Mandatory| Description                                                                 |
367| ------ | --------- | ---- | -------------------------------------------------------------------- |
368| 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).  |
369| args   | unknown[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
370
371**Error codes**
372
373For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
374
375| ID| Error Message                                |
376| -------- | --------------------------------------- |
377| 10200014 | The function is not mark as concurrent. |
378
379**Example**
380
381```ts
382@Concurrent
383function printArgs(args: number): number {
384  console.log("printArgs: " + args);
385  return args;
386}
387
388let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task");
389```
390
391### isCanceled<sup>10+</sup>
392
393static isCanceled(): boolean
394
395Checks whether the running task is canceled. Before using this API, you must create a **Task** instance.
396
397**System capability**: SystemCapability.Utils.Lang
398
399**Return value**
400
401| Type   | Description                                |
402| ------- | ------------------------------------ |
403| boolean | Returns **true** if the running task is canceled; returns **false** otherwise.|
404
405**Example**
406
407```ts
408@Concurrent
409function inspectStatus(arg: number): number {
410    // do something
411    if (taskpool.Task.isCanceled()) {
412      console.log("task has been canceled.");
413      // do something
414      return arg + 1;
415    }
416    // do something
417    return arg;
418}
419```
420
421> **NOTE**<br>
422> **isCanceled** must be used together with **taskpool.cancel**. If **cancel** is not called, **isCanceled** returns **false** by default.
423
424**Example**
425
426```ts
427@Concurrent
428function inspectStatus(arg: number): number {
429  // Check the cancellation status and return the result.
430  if (taskpool.Task.isCanceled()) {
431    console.log("task has been canceled before 2s sleep.");
432    return arg + 2;
433  }
434  // Wait for 2s.
435  let t: number = Date.now();
436  while (Date.now() - t < 2000) {
437    continue;
438  }
439  // Check the cancellation status again and return the result.
440  if (taskpool.Task.isCanceled()) {
441    console.log("task has been canceled after 2s sleep.");
442    return arg + 3;
443  }
444  return arg + 1;
445}
446
447let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
448taskpool.execute(task).then((res: number)=>{
449  console.log("taskpool test result: " + res);
450}).catch((err: string) => {
451  console.log("taskpool test occur error: " + err);
452});
453// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101.
454```
455
456### setTransferList<sup>10+</sup>
457
458setTransferList(transfer?: ArrayBuffer[]): void
459
460Sets the task transfer list. Before using this API, you must create a **Task** instance.
461
462> **NOTE**<br>
463> 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.
464
465**System capability**: SystemCapability.Utils.Lang
466
467**Parameters**
468
469| Name  | Type          | Mandatory| Description                                         |
470| -------- | ------------- | ---- | --------------------------------------------- |
471| transfer | ArrayBuffer[] | No  | **ArrayBuffer** instance holding the objects to transfer. The default value is an empty array.|
472
473**Example**
474
475```ts
476let buffer: ArrayBuffer = new ArrayBuffer(8);
477let view: Uint8Array = new Uint8Array(buffer);
478let buffer1: ArrayBuffer = new ArrayBuffer(16);
479let view1: Uint8Array = new Uint8Array(buffer1);
480
481console.info("testTransfer view byteLength: " + view.byteLength);
482console.info("testTransfer view1 byteLength: " + view1.byteLength);
483@Concurrent
484function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number {
485  console.info("testTransfer arg1 byteLength: " + arg1.byteLength);
486  console.info("testTransfer arg2 byteLength: " + arg2.byteLength);
487  return 100;
488}
489let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1);
490task.setTransferList([view.buffer, view1.buffer]);
491taskpool.execute(task).then((res: number)=>{
492  console.info("test result: " + res);
493}).catch((e: string)=>{
494  console.error("test catch: " + e);
495})
496console.info("testTransfer view byteLength: " + view.byteLength);
497console.info("testTransfer view1 byteLength: " + view1.byteLength);
498```
499
500### Attributes
501
502**System capability**: SystemCapability.Utils.Lang
503
504| Name     | Type     | Readable| Writable| Description                                                                      |
505| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- |
506| 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).  |
507| arguments | unknown[] | Yes  | Yes  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).|
508
509## TaskGroup<sup>10+</sup>
510
511Implements a task group. Before calling any APIs in **TaskGroup**, you must use [constructor](#constructor10) to create a **TaskGroup** instance.
512
513### constructor<sup>10+</sup>
514
515constructor()
516
517Constructor used to create a **TaskGroup** instance.
518
519**System capability**: SystemCapability.Utils.Lang
520
521**Example**
522
523```ts
524let taskGroup = new taskpool.TaskGroup();
525```
526
527### addTask<sup>10+</sup>
528
529addTask(func: Function, ...args: unknown[]): void
530
531Adds the function to be executed to this task group. Before using this API, you must create a **TaskGroup** instance.
532
533**System capability**: SystemCapability.Utils.Lang
534
535**Parameters**
536
537| Name| Type     | Mandatory| Description                                                                  |
538| ------ | --------- | ---- | ---------------------------------------------------------------------- |
539| 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).    |
540| args   | unknown[] | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
541
542**Error codes**
543
544For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
545
546| ID| Error Message                                |
547| -------- | --------------------------------------- |
548| 10200014 | The function is not mark as concurrent. |
549
550**Example**
551
552```ts
553@Concurrent
554function printArgs(args: number): number {
555  console.log("printArgs: " + args);
556  return args;
557}
558
559let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
560taskGroup.addTask(printArgs, 100); // 100: test number
561```
562
563### addTask<sup>10+</sup>
564
565addTask(task: Task): void
566
567Adds a created task to this task group. Before using this API, you must create a **TaskGroup** instance.
568
569**System capability**: SystemCapability.Utils.Lang
570
571**Parameters**
572
573| Name  | Type                 | Mandatory| Description                                      |
574| -------- | --------------------- | ---- | ---------------------------------------- |
575| task     | [Task](#task)         | Yes  | Task to be added to the task group.                 |
576
577**Error codes**
578
579For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
580
581| ID| Error Message                                |
582| -------- | --------------------------------------- |
583| 10200014 | The function is not mark as concurrent. |
584
585**Example**
586
587```ts
588@Concurrent
589function printArgs(args: number): number {
590  console.log("printArgs: " + args);
591  return args;
592}
593
594let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
595let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
596taskGroup.addTask(task);
597```
598
599
600## State<sup>10+</sup>
601
602Enumerates the task states.
603
604**System capability**: SystemCapability.Utils.Lang
605
606| Name     | Value       | Description         |
607| --------- | -------- | ------------- |
608| WAITING   | 1        | The task is waiting.|
609| RUNNING   | 2        | The task is running.|
610| CANCELED  | 3        | The task is canceled.|
611
612
613## TaskInfo<sup>10+</sup>
614
615Describes the internal information about a task.
616
617**System capability**: SystemCapability.Utils.Lang
618
619### Attributes
620
621**System capability**: SystemCapability.Utils.Lang
622
623| Name    | Type               | Readable| Writable| Description                                                          |
624| -------- | ------------------ | ---- | ---- | ------------------------------------------------------------- |
625| taskId   | number             | Yes  | No  | Task ID.                                                    |
626| state    | [State](#state10)  | Yes  | No  | Task state.                                                   |
627| 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. |
628
629## ThreadInfo<sup>10+</sup>
630
631Describes the internal information about a worker thread.
632
633**System capability**: SystemCapability.Utils.Lang
634
635### Attributes
636
637**System capability**: SystemCapability.Utils.Lang
638
639| Name    | Type                   | Readable| Writable| Description                                                     |
640| -------- | ---------------------- | ---- | ---- | -------------------------------------------------------- |
641| tid      | number                 | Yes  | No  | ID of the worker thread. If the return value is empty, no task is running.             |
642| taskIds  | number[]               | Yes  | No  | IDs of tasks running on the calling thread. If the return value is empty, no task is running.  |
643| priority | [Priority](#priority)  | Yes  | No  | Priority of the calling thread. If the return value is empty, no task is running.             |
644
645## TaskPoolInfo<sup>10+</sup>
646
647Describes the internal information about a task pool.
648
649**System capability**: SystemCapability.Utils.Lang
650
651### Attributes
652
653**System capability**: SystemCapability.Utils.Lang
654
655| Name         | Type                             | Readable| Writable| Description                 |
656| ------------- | -------------------------------- | ---- | ---- | -------------------- |
657| threadInfos   | [ThreadInfo[]](#threadinfo10)    | Yes  | No  | Internal information about the worker threads.  |
658| taskInfos     | [TaskInfo[]](#taskinfo10)        | Yes  | No  | Internal information about the tasks.      |
659
660
661## Additional Information
662
663### Sequenceable Data Types
664The following sequenceable data types are supported: All Primitive Type (excluding symbol), Date, String, RegExp, Array, Map, Set, Object, ArrayBuffer, and TypedArray.
665
666### Using the Task Pool in Simple Mode
667
668**Example 1**
669
670```ts
671// Common functions are supported, and variables passed in by input parameters are also supported.
672@Concurrent
673function printArgs(args: number): number {
674  console.log("func: " + args);
675  return args;
676}
677async function taskpoolExecute(): Promise<void> {
678  // taskpool.execute(task)
679  let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
680  console.log("taskpool.execute(task) result: " + await taskpool.execute(task));
681  // taskpool.execute(function)
682  console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
683}
684taskpoolExecute();
685```
686
687**Example 2**
688
689```ts
690// b.ets
691export let c: string = "hello";
692```
693```ts
694// Reference an imported variable.
695// a.ets (in the same directory as b.ets)
696import { c } from "./b";
697
698@Concurrent
699function printArgs(a: string): string {
700    console.log(a);
701    console.log(c);
702    return a;
703}
704
705async function taskpoolExecute(): Promise<void> {
706  // taskpool.execute(task)
707  let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
708  console.log("taskpool.execute(task) result: " + await taskpool.execute(task));
709
710  // taskpool.execute(function)
711  console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
712}
713
714taskpoolExecute();
715```
716
717**Example 3**
718
719```ts
720// The async functions are supported.
721@Concurrent
722async function delayExcute(): Promise<Object> {
723  let ret = await Promise.all<Object>([
724    new Promise<Object>(resolve => setTimeout(resolve, 1000, "resolved"))
725  ]);
726  return ret;
727}
728
729async function taskpoolExecute(): Promise<void> {
730  taskpool.execute(delayExcute).then((result: string) => {
731    console.log("taskPoolTest task result: " + result);
732  }).catch((err: string) => {
733    console.log("taskpool test occur error: " + err);
734  });
735}
736
737taskpoolExecute();
738```
739
740**Example 4**
741
742```ts
743// c.ets
744@Concurrent
745function strSort(inPutArr: Array<string>): Array<string> {
746  let newArr = inPutArr.sort();
747  return newArr;
748}
749export async function func1(): Promise<void> {
750  console.log("taskpoolTest start");
751  let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
752  let task: taskpool.Task = new taskpool.Task(strSort, strArray);
753  console.log("func1 result:" + await taskpool.execute(task));
754}
755
756export async function func2(): Promise<void> {
757  console.log("taskpoolTest2 start");
758  let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
759  taskpool.execute(strSort, strArray).then((result: Array<string>) => {
760    console.log("func2 result: " + result);
761  }).catch((err: string) => {
762    console.log("taskpool test occur error: " + err);
763  });
764}
765```
766
767```ts
768// a.ets (in the same directory as c.ets)
769import { func1, func2 } from "./c";
770
771func1();
772func2();
773```
774
775**Example 5**
776
777```ts
778// Success in canceling a task
779@Concurrent
780function inspectStatus(arg: number): number {
781  // Check the cancellation status and return the result.
782  if (taskpool.Task.isCanceled()) {
783    console.log("task has been canceled before 2s sleep.");
784    return arg + 2;
785  }
786  // 2s sleep
787  let t: number = Date.now();
788  while (Date.now() - t < 2000) {
789    continue;
790  }
791  // Check the cancellation status again and return the result.
792  if (taskpool.Task.isCanceled()) {
793    console.log("task has been canceled after 2s sleep.");
794    return arg + 3;
795  }
796  return arg + 1;
797}
798
799async function taskpoolCancel(): Promise<void> {
800  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
801  taskpool.execute(task).then((res: number)=>{
802    console.log("taskpool test result: " + res);
803  }).catch((err: string) => {
804    console.log("taskpool test occur error: " + err);
805  });
806  // Cancel the task 1s later.
807  setTimeout(()=>{
808    taskpool.cancel(task);}, 1000);
809}
810
811taskpoolCancel();
812```
813
814**Example 6**
815
816```ts
817// Failure to cancel a task that has been executed
818@Concurrent
819function inspectStatus(arg: number): number {
820  // Check the cancellation status and return the result.
821  if (taskpool.Task.isCanceled()) {
822    return arg + 2;
823  }
824  // Wait for 2s.
825  let t: number = Date.now();
826  while (Date.now() - t < 500) {
827    continue;
828  }
829  // Check the cancellation status again and return the result.
830  if (taskpool.Task.isCanceled()) {
831    return arg + 3;
832  }
833  return arg + 1;
834}
835
836async function taskpoolCancel(): Promise<void> {
837  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
838  taskpool.execute(task).then((res: number)=>{
839    console.log("taskpool test result: " + res);
840  }).catch((err: string) => {
841    console.log("taskpool test occur error: " + err);
842  });
843
844  setTimeout(()=>{
845    try {
846      taskpool.cancel(task); // The task has been executed and fails to be canceled.
847    } catch (e) {
848      console.log("taskpool.cancel occur error:" + e);
849    }
850  }, 3000); // Wait for 3s to ensure that the task has been executed.
851}
852
853taskpoolCancel();
854```
855
856**Example 7**
857
858```ts
859// Success of canceling a task group to be executed
860@Concurrent
861function printArgs(args: number): number {
862  let t: number = Date.now();
863  while (Date.now() - t < 1000) {
864    continue;
865  }
866  console.log("printArgs: " + args);
867  return args;
868}
869
870async function taskpoolGroupCancelTest(): Promise<void> {
871  let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
872  taskGroup1.addTask(printArgs, 10); // 10: test number
873  taskGroup1.addTask(printArgs, 20); // 20: test number
874  taskGroup1.addTask(printArgs, 30); // 30: test number
875  let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
876  let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
877  let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
878  let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
879  taskGroup2.addTask(task1);
880  taskGroup2.addTask(task2);
881  taskGroup2.addTask(task3);
882  taskpool.execute(taskGroup1).then((res: Array<number>) => {
883    console.info("taskpool execute res is:" + res);
884  }).catch((e: string) => {
885    console.error("taskpool execute error is:" + e);
886  });
887  taskpool.execute(taskGroup2).then((res: Array<number>) => {
888    console.info("taskpool execute res is:" + res);
889  }).catch((e: string) => {
890    console.error("taskpool execute error is:" + e);
891  });
892
893  taskpool.cancel(taskGroup2);
894}
895
896taskpoolGroupCancelTest()
897```
898
899**Example 8**
900
901```ts
902// Create and execute 100 tasks with different priorities, and view their information.
903@Concurrent
904function delay(): void {
905  let start: number = new Date().getTime();
906  while (new Date().getTime() - start < 500) {
907    continue;
908  }
909}
910
911let highCount: number = 0;
912let mediumCount: number = 0;
913let lowCount: number = 0;
914let allCount: number = 100;
915for (let i = 0; i < allCount; i++) {
916  let task1: taskpool.Task = new taskpool.Task(delay);
917  let task2: taskpool.Task = new taskpool.Task(delay);
918  let task3: taskpool.Task = new taskpool.Task(delay);
919  taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
920    lowCount++;
921  }).catch((e: string) => {
922    console.error("low task error: " + e);
923  })
924  taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
925    mediumCount++;
926  }).catch((e: string) => {
927    console.error("medium task error: " + e);
928  })
929  taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
930    highCount++;
931  }).catch((e: string) => {
932    console.error("high task error: " + e);
933  })
934}
935let start: number = new Date().getTime();
936while (new Date().getTime() - start < 1000) {
937  continue;
938}
939let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
940let tid: number = 0;
941let taskIds: Array<number> = [];
942let priority: number = 0;
943let taskId: number = 0;
944let state: number = 0;
945let duration: number = 0;
946let threadIS = Array.from(taskpoolInfo.threadInfos)
947for(let threadInfo of threadIS) {
948  tid = threadInfo.tid;
949  if (threadInfo.taskIds != undefined && threadInfo.priority != undefined )
950  {
951    taskIds.length = threadInfo.taskIds.length;
952    priority = threadInfo.priority;
953  }
954  console.info("taskpool---tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority);
955}
956let taskIS = Array.from(taskpoolInfo.taskInfos)
957for(let taskInfo of taskIS) {
958  taskId = taskInfo.taskId;
959  state = taskInfo.state;
960  if (taskInfo.duration != undefined )
961  {
962    duration = taskInfo.duration;
963  }
964  console.info("taskpool---taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration);
965}
966```
967