• 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](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
13The following concepts are used in this topic:
14- Task group task: task in a [TaskGroup](#taskgroup10).
15- Serial queue task: task in a [SequenceRunner](#sequencerunner-11).
16- Asynchronous queue task: task in an [AsyncRunner](#asyncrunner18).
17- Periodic task: task executed by calling [executePeriodically](#taskpoolexecuteperiodically12).
18
19> **NOTE**
20>
21> 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.
22
23## Modules to Import
24
25```ts
26import { taskpool } from '@kit.ArkTS';
27```
28## taskpool.execute
29
30execute(func: Function, ...args: Object[]): Promise\<Object>
31
32Places a function to be executed in the internal queue of the task pool. The function is not executed immediately. It waits to be distributed to the worker thread for execution. In this mode, the function cannot be canceled.
33
34**System capability**: SystemCapability.Utils.Lang
35
36**Atomic service API**: This API can be used in atomic services since API version 11.
37
38**Parameters**
39
40| Name| Type     | Mandatory| Description                                                                  |
41| ------ | --------- | ---- | ---------------------------------------------------------------------- |
42| func   | Function  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
43| 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**.|
44
45**Return value**
46
47| Type             | Description                                |
48| ----------------- | ------------------------------------ |
49| Promise\<Object>  | Promise used to return an object that carries the function execution result.|
50
51**Error codes**
52
53For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
54
55| ID| Error Message                                     |
56| -------- | -------------------------------------------- |
57| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
58| 10200006 | An exception occurred during serialization.  |
59| 10200014 | The function is not marked as concurrent.      |
60
61**Example**
62
63```ts
64@Concurrent
65function printArgs(args: number): number {
66    console.info("printArgs: " + args);
67    return args;
68}
69
70taskpool.execute(printArgs, 100).then((value: Object) => { // 100: test number
71  console.info("taskpool result: " + value);
72});
73```
74
75
76## taskpool.execute<sup>13+</sup>
77
78execute<A extends Array\<Object>, R>(func: (...args: A) => R | Promise\<R>, ...args: A): Promise\<R>
79
80Verifies the passed-in parameter types and return value type of a concurrent function, and places the function to execute in the internal queue of the task pool.
81
82**System capability**: SystemCapability.Utils.Lang
83
84**Atomic service API**: This API can be used in atomic services since API version 13.
85
86**Parameters**
87
88| Name| Type     | Mandatory| Description                                                                  |
89| ------ | --------- | ---- | ---------------------------------------------------------------------- |
90| func   | (...args: A) => R \| Promise\<R>  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
91| args   | A | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
92
93**Return value**
94
95| Type             | Description                                |
96| ----------------- | ------------------------------------ |
97| Promise\<R>  | Promise used to return an object that carries the function execution result.|
98
99**Error codes**
100
101For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
102
103| ID| Error Message                                     |
104| -------- | -------------------------------------------- |
105| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
106| 10200006 | An exception occurred during serialization.  |
107| 10200014 | The function is not marked as concurrent.      |
108
109**Example**
110
111```ts
112@Concurrent
113function printArgs(args: number): number {
114    console.info("printArgs: " + args);
115    return args;
116}
117
118@Concurrent
119function testWithThreeParams(a: number, b: string, c: number): string {
120  return b;
121}
122
123@Concurrent
124function testWithArray(args: [number, string]): string {
125  return "success";
126}
127
128taskpool.execute<[number], number>(printArgs, 100).then((value: number) => { // 100: test number
129  console.info("taskpool result: " + value);
130});
131
132taskpool.execute<[number, string, number], string>(testWithThreeParams, 100, "test", 100).then((value: string) => {})
133
134taskpool.execute<[[number, string]], string>(testWithArray, [100, "test"]).then((value: string) => {})
135```
136
137
138## taskpool.execute
139
140execute(task: Task, priority?: Priority): Promise\<Object>
141
142Places a task in the internal queue of the task pool. The task is not executed immediately. It waits to be distributed to the worker thread for execution. In this mode, you can set the task priority and call **cancel()** to cancel the task. The task cannot be a task in a task group, serial queue, or asynchronous queue. This API can be called only once for a continuous task, but multiple times for a non-continuous task.
143
144**System capability**: SystemCapability.Utils.Lang
145
146**Atomic service API**: This API can be used in atomic services since API version 11.
147
148**Parameters**
149
150| Name  | Type                 | Mandatory| Description                                      |
151| -------- | --------------------- | ---- | ---------------------------------------- |
152| task     | [Task](#task)         | Yes  | Task to be executed.                 |
153| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
154
155**Return value**
156
157| Type             | Description             |
158| ----------------  | ---------------- |
159| Promise\<Object> | Promise used to return an object that carries the function execution result.|
160
161**Error codes**
162
163For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
164
165| ID| Error Message                                    |
166| -------- | ------------------------------------------- |
167| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
168| 10200006 | An exception occurred during serialization. |
169| 10200014 | The function is not marked as concurrent.     |
170| 10200051 | The periodic task cannot be executed again. |
171| 10200057 | The task cannot be executed by two APIs.  |
172
173**Example**
174
175```ts
176@Concurrent
177function printArgs(args: number): number {
178    console.info("printArgs: " + args);
179    return args;
180}
181
182let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
183let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
184let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
185taskpool.execute(task1, taskpool.Priority.LOW).then((value: Object) => {
186  console.info("taskpool result1: " + value);
187});
188taskpool.execute(task2, taskpool.Priority.MEDIUM).then((value: Object) => {
189  console.info("taskpool result2: " + value);
190});
191taskpool.execute(task3, taskpool.Priority.HIGH).then((value: Object) => {
192  console.info("taskpool result3: " + value);
193});
194```
195
196
197## taskpool.execute<sup>13+</sup>
198
199execute<A extends Array\<Object>, R>(task: GenericsTask<A, R>, priority?: Priority): Promise\<R>
200
201Verifies the passed-in parameter types and return value type of a concurrent function, and places the generic task in the internal queue of the task pool.
202
203**System capability**: SystemCapability.Utils.Lang
204
205**Atomic service API**: This API can be used in atomic services since API version 13.
206
207**Parameters**
208
209| Name  | Type                 | Mandatory| Description                                      |
210| -------- | --------------------- | ---- | ---------------------------------------- |
211| task     | [GenericsTask](#genericstask13)         | Yes  | Generic task to be executed.                 |
212| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
213
214**Return value**
215
216| Type             | Description             |
217| ----------------  | ---------------- |
218| Promise\<R> | Promise used to return an object that carries the function execution result.|
219
220**Error codes**
221
222For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
223
224| ID| Error Message                                    |
225| -------- | ------------------------------------------- |
226| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
227| 10200006 | An exception occurred during serialization. |
228| 10200014 | The function is not marked as concurrent.     |
229| 10200051 | The periodic task cannot be executed again. |
230| 10200057 | The task cannot be executed by two APIs.  |
231
232**Example**
233
234```ts
235@Concurrent
236function printArgs(args: number): number {
237    console.info("printArgs: " + args);
238    return args;
239}
240
241let task1: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 100); // 100: test number
242let task2: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 200); // 200: test number
243let task3: taskpool.Task = new taskpool.GenericsTask<[number], number>(printArgs, 300); // 300: test number
244taskpool.execute<[number], number>(task1, taskpool.Priority.LOW).then((value: number) => {
245  console.info("taskpool result1: " + value);
246});
247taskpool.execute<[number], number>(task2, taskpool.Priority.MEDIUM).then((value: number) => {
248  console.info("taskpool result2: " + value);
249});
250taskpool.execute<[number], number>(task3, taskpool.Priority.HIGH).then((value: number) => {
251  console.info("taskpool result3: " + value);
252});
253```
254
255
256## taskpool.execute<sup>10+</sup>
257
258execute(group: TaskGroup, priority?: Priority): Promise<Object[]>
259
260Places a task group in the internal queue of the task pool. The tasks in the task group are not executed immediately. They wait to be distributed to the worker thread for execution. After all tasks in the task group are executed, a result array is returned. This API applies when you want to execute a group of associated tasks.
261
262**System capability**: SystemCapability.Utils.Lang
263
264**Atomic service API**: This API can be used in atomic services since API version 11.
265
266**Parameters**
267
268| Name    | Type                       | Mandatory| Description                                                          |
269| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
270| group     | [TaskGroup](#taskgroup10)     | Yes  | Task group to be executed.                                     |
271| priority  | [Priority](#priority)       | No  | Priority of the task group. The default value is **taskpool.Priority.MEDIUM**.|
272
273**Return value**
274
275| Type                | Description                              |
276| ----------------    | ---------------------------------- |
277| Promise\<Object[]>  | Promise used to return an object array that carries the function execution result.|
278
279**Error codes**
280
281For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
282
283| ID| Error Message                                    |
284| -------- | ------------------------------------------- |
285| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
286| 10200006 | An exception occurred during serialization. |
287
288**Example**
289
290```ts
291@Concurrent
292function printArgs(args: number): number {
293    console.info("printArgs: " + args);
294    return args;
295}
296
297let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
298taskGroup1.addTask(printArgs, 10); // 10: test number
299taskGroup1.addTask(printArgs, 20); // 20: test number
300taskGroup1.addTask(printArgs, 30); // 30: test number
301
302let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
303let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
304let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
305let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
306taskGroup2.addTask(task1);
307taskGroup2.addTask(task2);
308taskGroup2.addTask(task3);
309taskpool.execute(taskGroup1).then((res: Array<Object>) => {
310  console.info("taskpool execute res is:" + res);
311});
312taskpool.execute(taskGroup2).then((res: Array<Object>) => {
313  console.info("taskpool execute res is:" + res);
314});
315```
316
317## taskpool.executeDelayed<sup>11+</sup>
318
319executeDelayed(delayTime: number, task: Task, priority?: Priority): Promise\<Object>
320
321Executes a task after a given delay. In this mode, you can set the task priority and call **cancel()** to cancel the task. The task cannot be a task in a task group, serial queue, or asynchronous queue, or a periodic task. This API can be called only once for a continuous task, but multiple times for a non-continuous task.
322
323**System capability**: SystemCapability.Utils.Lang
324
325**Atomic service API**: This API can be used in atomic services since API version 11.
326
327**Parameters**
328
329| Name      | Type         | Mandatory| Description                |
330| ----------- | ------------- | ---- | -------------------- |
331| delayTime   | number        | Yes  | Delay, in ms. |
332| task        | [Task](#task) | Yes  | Task to be executed with a delay.|
333| priority    | [Priority](#priority)       | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
334
335**Return value**
336
337| Type                | Description                              |
338| ----------------    | ---------------------------------- |
339| Promise\<Object>  | Promise used to return an object that carries the function execution result.|
340
341**Error codes**
342
343For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
344
345| ID  | Error Message                        |
346| --------- | -------------------------------- |
347| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
348| 10200006 | An exception occurred during serialization. |
349| 10200014 | The function is not marked as concurrent. |
350| 10200028 | The delayTime is less than zero. |
351| 10200051 | The periodic task cannot be executed again. |
352| 10200057 | The task cannot be executed by two APIs.  |
353
354**Example**
355
356```ts
357// import BusinessError
358import { BusinessError } from '@kit.BasicServicesKit'
359
360@Concurrent
361function printArgs(args: number): void {
362    console.info("printArgs: " + args);
363}
364
365let t: number = Date.now();
366console.info("taskpool start time is: " + t);
367let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
368taskpool.executeDelayed(1000, task).then(() => { // 1000:delayTime is 1000ms
369  console.info("taskpool execute success");
370}).catch((e: BusinessError) => {
371  console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`);
372})
373```
374
375
376## taskpool.executeDelayed<sup>13+</sup>
377
378executeDelayed<A extends Array\<Object>, R>(delayTime: number, task: GenericsTask\<A, R>, priority?: Priority): Promise\<R>
379
380Verifies the passed-in parameter types and return value type of a concurrent function, and executes the generic task with a delay.
381
382**System capability**: SystemCapability.Utils.Lang
383
384**Atomic service API**: This API can be used in atomic services since API version 13.
385
386**Parameters**
387
388| Name      | Type         | Mandatory| Description                |
389| ----------- | ------------- | ---- | -------------------- |
390| delayTime   | number        | Yes  | Delay, in ms. |
391| task        | [GenericsTask](#genericstask13) | Yes  | Generic task to be executed with a delay.|
392| priority    | [Priority](#priority)       | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
393
394**Return value**
395
396| Type                | Description                              |
397| ----------------    | ---------------------------------- |
398| Promise\<R>  | Promise used to return an object that carries the function execution result.|
399
400**Error codes**
401
402For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
403
404| ID  | Error Message                        |
405| --------- | -------------------------------- |
406| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
407| 10200028 | The delayTime is less than zero. |
408| 10200051 | The periodic task cannot be executed again. |
409| 10200057 | The task cannot be executed by two APIs.  |
410
411**Example**
412
413```ts
414// import BusinessError
415import { BusinessError } from '@kit.BasicServicesKit'
416
417@Concurrent
418function printArgs(args: number): string {
419    console.info("printArgs: " + args);
420    return "success";
421}
422
423let task: taskpool.Task = new taskpool.GenericsTask<[number], string>(printArgs, 100); // 100: test number
424taskpool.executeDelayed<[number], string>(1000, task).then((res: string) => { // 1000:delayTime is 1000ms
425  console.info("taskpool execute success");
426}).catch((e: BusinessError) => {
427  console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`);
428})
429```
430
431
432## taskpool.executePeriodically<sup>12+</sup>
433
434executePeriodically(period: number, task: Task, priority?: Priority): void
435
436Executes a task periodically.
437
438In this execution mode, you can set the task priority and call **cancel()** to cancel the execution.
439
440A periodic task cannot be a task in a task group, serial queue, or asynchronous queue. It cannot call **execute()** again or have a dependency relationship.
441
442
443**System capability**: SystemCapability.Utils.Lang
444
445**Atomic service API**: This API can be used in atomic services since API version 12.
446
447**Parameters**
448
449| Name      | Type         | Mandatory | Description                |
450| -----------  | ------------- | ----- | -------------------- |
451| period       | number        | Yes   | Execution period, in ms. |
452| task         | [Task](#task) | Yes   | Task to be executed.|
453| priority     | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
454
455
456**Error codes**
457
458For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
459
460| ID  | Error Message                        |
461| ---------- | -------------------------------- |
462| 401        | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
463| 10200006   | An exception occurred during serialization. |
464| 10200014   | The function is not marked as concurrent. |
465| 10200028   | The period is less than zero. |
466| 10200050   | The concurrent task has been executed and cannot be executed periodically. |
467| 10200057 | The task cannot be executed by two APIs.  |
468
469
470**Example**
471
472```ts
473@Concurrent
474function printArgs(args: number): void {
475  console.info("printArgs: " + args);
476}
477
478@Concurrent
479function testExecutePeriodically(args: number): void {
480  let t = Date.now();
481  while ((Date.now() - t) < args) {
482    continue;
483  }
484  taskpool.Task.sendData(args); // Send a message to the host thread.
485}
486
487function printResult(data: number): void {
488  console.info("taskpool: data is: " + data);
489}
490
491function taskpoolTest() {
492  try {
493    let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
494    taskpool.executePeriodically(1000, task); // 1000: period is 1000ms
495  } catch (e) {
496    console.error(`taskpool execute-1: Code: ${e.code}, message: ${e.message}`);
497  }
498
499  try {
500    let periodicTask: taskpool.Task = new taskpool.Task(testExecutePeriodically, 200); // 200: test number
501    periodicTask.onReceiveData(printResult);
502    taskpool.executePeriodically(1000, periodicTask); // 1000: period is 1000ms
503  } catch (e) {
504    console.error(`taskpool execute-2: Code: ${e.code}, message: ${e.message}`);
505  }
506}
507
508taskpoolTest();
509```
510
511
512## taskpool.executePeriodically<sup>13+</sup>
513
514executePeriodically<A extends Array\<Object>, R>(period: number, task: GenericsTask\<A, R>, priority?: Priority): void
515
516Verifies the passed-in parameter types and return value type of a concurrent function, and executes the generic task periodically at an interval specified by **period**.
517
518
519**System capability**: SystemCapability.Utils.Lang
520
521**Atomic service API**: This API can be used in atomic services since API version 13.
522
523**Parameters**
524
525| Name      | Type         | Mandatory | Description                |
526| -----------  | ------------- | ----- | -------------------- |
527| period       | number        | Yes   | Execution period, in ms. |
528| task         | [GenericsTask](#genericstask13) | Yes   | Generic task to be executed periodically.|
529| priority     | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
530
531
532**Error codes**
533
534For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
535
536| ID  | Error Message                        |
537| ---------- | -------------------------------- |
538| 401        | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
539| 10200006   | An exception occurred during serialization. |
540| 10200014   | The function is not marked as concurrent. |
541| 10200028   | The period is less than zero. |
542| 10200050   | The concurrent task has been executed and cannot be executed periodically. |
543| 10200057 | The task cannot be executed by two APIs.  |
544
545
546**Example**
547
548```ts
549@Concurrent
550function printArgs(args: number): void {
551  console.info("printArgs: " + args);
552}
553
554@Concurrent
555function testExecutePeriodically(args: number): void {
556  let t = Date.now();
557  while ((Date.now() - t) < args) {
558    continue;
559  }
560  taskpool.Task.sendData(args); // Send a message to the host thread.
561}
562
563function printResult(data: number): void {
564  console.info("taskpool: data is: " + data);
565}
566
567function taskpoolTest() {
568  try {
569    let task: taskpool.Task = new taskpool.GenericsTask<[number], void>(printArgs, 100); // 100: test number
570    taskpool.executePeriodically<[number], void>(1000, task); // 1000: period is 1000ms
571  } catch (e) {
572    console.error(`taskpool execute-1: Code: ${e.code}, message: ${e.message}`);
573  }
574
575  try {
576    let periodicTask: taskpool.Task = new taskpool.GenericsTask<[number], void>(testExecutePeriodically, 200); // 200: test number
577    periodicTask.onReceiveData(printResult);
578    taskpool.executePeriodically<[number], void>(1000, periodicTask); // 1000: period is 1000ms
579  } catch (e) {
580    console.error(`taskpool execute-2: Code: ${e.code}, message: ${e.message}`);
581  }
582}
583
584taskpoolTest();
585```
586
587
588## taskpool.cancel
589
590cancel(task: Task): void
591
592Cancels a task in the task pool. If the task is in the internal queue of the task pool, the task will not be executed after being canceled, and an exception indicating task cancellation is returned. If the task has been distributed to the worker thread of the task pool, canceling the task does not affect the task execution, and the execution result is returned in the catch branch. You can use **isCanceled()** to check the task cancellation status. In other words, **taskpool.cancel** takes effect before **taskpool.execute** or **taskpool.executeDelayed** is called.
593
594**System capability**: SystemCapability.Utils.Lang
595
596**Atomic service API**: This API can be used in atomic services since API version 11.
597
598**Parameters**
599
600| Name| Type         | Mandatory| Description                |
601| ------ | ------------- | ---- | -------------------- |
602| task   | [Task](#task) | Yes  | Task to cancel.|
603
604**Error codes**
605
606For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
607
608| ID| Error Message                                     |
609| -------- | -------------------------------------------- |
610| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
611| 10200015 | The task to cancel does not exist. |
612| 10200055 | The asyncRunner task has been canceled. |
613
614Since API version 10, error code 10200016 is not reported when this API is called.
615
616**Example of canceling an ongoing task**
617
618```ts
619@Concurrent
620function inspectStatus(arg: number): number {
621  // Check whether the task has been canceled and respond accordingly.
622  if (taskpool.Task.isCanceled()) {
623    console.info("task has been canceled before 2s sleep.");
624    return arg + 2;
625  }
626  // 2s sleep
627  let t: number = Date.now();
628  while (Date.now() - t < 2000) {
629    continue;
630  }
631  // Check again whether the task has been canceled and respond accordingly.
632  if (taskpool.Task.isCanceled()) {
633    console.info("task has been canceled after 2s sleep.");
634    return arg + 3;
635  }
636  return arg + 1;
637}
638
639function concurrentFunc() {
640  let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
641  let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number
642  let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number
643  let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number
644  let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number
645  let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number
646  taskpool.execute(task1).then((res: Object)=>{
647    console.info("taskpool test result: " + res);
648  });
649  taskpool.execute(task2);
650  taskpool.execute(task3);
651  taskpool.execute(task4);
652  taskpool.execute(task5);
653  taskpool.execute(task6);
654  // Cancel the task 1s later.
655  setTimeout(()=>{
656    try {
657      taskpool.cancel(task1);
658    } catch (e) {
659      console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
660    }
661  }, 1000);
662}
663
664concurrentFunc();
665```
666
667## taskpool.cancel<sup>10+</sup>
668
669cancel(group: TaskGroup): void
670
671Cancels a task group in the task pool. If a task group is canceled before all the tasks in it are finished, **undefined** is returned.
672
673**System capability**: SystemCapability.Utils.Lang
674
675**Atomic service API**: This API can be used in atomic services since API version 11.
676
677**Parameters**
678
679| Name  | Type                   | Mandatory| Description                |
680| ------- | ----------------------- | ---- | -------------------- |
681| group   | [TaskGroup](#taskgroup10) | Yes  | Task group to cancel.|
682
683**Error codes**
684
685For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
686
687| ID| Error Message                                                |
688| -------- | ------------------------------------------------------- |
689| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
690| 10200018 | The task group to cancel does not exist.      |
691
692**Example**
693
694```ts
695@Concurrent
696function printArgs(args: number): number {
697  let t: number = Date.now();
698  while (Date.now() - t < 2000) {
699    continue;
700  }
701  console.info("printArgs: " + args);
702  return args;
703}
704
705function concurrentFunc() {
706  let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
707  taskGroup1.addTask(printArgs, 10); // 10: test number
708  let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
709  taskGroup2.addTask(printArgs, 100); // 100: test number
710  taskpool.execute(taskGroup1).then((res: Array<Object>)=>{
711    console.info("taskGroup1 res is:" + res);
712  });
713  taskpool.execute(taskGroup2).then((res: Array<Object>)=>{
714    console.info("taskGroup2 res is:" + res);
715  });
716  setTimeout(()=>{
717    try {
718      taskpool.cancel(taskGroup2);
719    } catch (e) {
720      console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
721    }
722  }, 1000);
723}
724
725concurrentFunc();
726```
727
728## taskpool.cancel<sup>18+</sup>
729
730cancel(taskId: number): void
731
732Cancels a task in the task pool by task ID. If the task is in the internal queue of the task pool, the task will not be executed after being canceled, and an exception indicating task cancellation is returned. If the task has been distributed to the worker thread of the task pool, canceling the task does not affect the task execution, and the execution result is returned in the catch branch. You can use **isCanceled()** to check the task cancellation status. In other words, **taskpool.cancel** takes effect before **taskpool.execute** or **taskpool.executeDelayed** is called. If **taskpool.cancel** is called by other threads, note that the cancel operation, which is asynchronous, may take effect for later calls of **taskpool.execute** or **taskpool.executeDelayed**.
733
734**System capability**: SystemCapability.Utils.Lang
735
736**Atomic service API**: This API can be used in atomic services since API version 18.
737
738**Parameters**
739
740| Name  | Type                   | Mandatory| Description                |
741| ------- | ----------------------- | ---- | -------------------- |
742| taskId   | number | Yes  | ID of the task to cancel.|
743
744**Error codes**
745
746For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
747
748| ID| Error Message                                     |
749| -------- | -------------------------------------------- |
750| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
751| 10200015 | The task to cancel does not exist. |
752| 10200055 | The asyncRunner task has been canceled. |
753
754**Example**
755
756```ts
757@Concurrent
758function printArgs(args: number): number {
759  let t: number = Date.now();
760  while (Date.now() - t < 2000) {
761    continue;
762  }
763  if (taskpool.Task.isCanceled()) {
764    console.info("task has been canceled after 2s sleep.");
765    return args + 1;
766  }
767  console.info("printArgs: " + args);
768  return args;
769}
770
771@Concurrent
772function cancelFunction(taskId: number) {
773  try {
774    taskpool.cancel(taskId);
775  } catch (e) {
776    console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
777  }
778}
779
780function concurrentFunc() {
781  let task = new taskpool.Task(printArgs, 100); // 100: test number
782  taskpool.execute(task);
783  setTimeout(()=>{
784    let cancelTask = new taskpool.Task(cancelFunction, task.taskId);
785    taskpool.execute(cancelTask);
786  }, 1000);
787}
788
789concurrentFunc();
790```
791
792## taskpool.terminateTask<sup>12+</sup>
793
794terminateTask(longTask: LongTask): void
795
796Terminates a continuous task in the task pool. It is called after the continuous task is complete. After the task is terminated, the thread that executes the task may be reclaimed.
797
798**System capability**: SystemCapability.Utils.Lang
799
800**Atomic service API**: This API can be used in atomic services since API version 12.
801
802**Parameters**
803
804| Name| Type         | Mandatory| Description                |
805| ------ | ------------- | ---- | -------------------- |
806| longTask   | [LongTask](#longtask12) | Yes  | Continuous task to terminate.|
807
808**Error codes**
809
810For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
811
812| ID| Error Message|
813| -------- | -------- |
814| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
815
816**Example**
817
818```ts
819@Concurrent
820function longTask(arg: number): number {
821  let t: number = Date.now();
822  while (Date.now() - t < arg) {
823    continue;
824  }
825  console.info("longTask has been executed.");
826  return arg;
827}
828
829function concurrentFunc() {
830  let task1: taskpool.LongTask = new taskpool.LongTask(longTask, 1000); // 1000: sleep time
831  taskpool.execute(task1).then((res: Object)=>{
832    taskpool.terminateTask(task1);
833    console.info("taskpool longTask result: " + res);
834  });
835}
836
837concurrentFunc();
838```
839
840## taskpool.isConcurrent<sup>12+</sup>
841
842isConcurrent(func: Function): boolean
843
844Checks whether a function is a concurrent function.
845
846**System capability**: SystemCapability.Utils.Lang
847
848**Atomic service API**: This API can be used in atomic services since API version 12.
849
850**Parameters**
851
852| Name| Type         | Mandatory| Description                |
853| ------ | ------------- | ---- | -------------------- |
854| func   | Function | Yes  | Function to check.|
855
856**Return value**
857
858| Type   | Description                                |
859| ------- | ------------------------------------ |
860| boolean | Check result. The value **true** means that the function is a concurrent function, that is, a function decorated with [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator); **false** means the opposite.|
861
862**Error codes**
863
864For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
865
866| ID| Error Message|
867| -------- | -------- |
868| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
869
870**Example**
871
872```ts
873@Concurrent
874function test() {}
875
876let result: Boolean = taskpool.isConcurrent(test)
877console.info("result is: " + result)
878```
879
880## taskpool.getTaskPoolInfo<sup>10+</sup>
881
882getTaskPoolInfo(): TaskPoolInfo
883
884Obtains internal information about this task pool, including thread information and task information.
885
886**System capability**: SystemCapability.Utils.Lang
887
888**Atomic service API**: This API can be used in atomic services since API version 11.
889
890**Return value**
891
892| Type                               | Description               |
893| ----------------------------------- | ------------------ |
894| [TaskPoolInfo](#taskpoolinfo10)   | Internal information about the task pool.  |
895
896**Example**
897
898```ts
899let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
900```
901
902## Priority
903
904Enumerates the priorities available for created tasks. The task priority applies during task execution. The worker thread priority is updated with the task priority. For details about the mappings, see [QoS Level](../../napi/qos-guidelines.md#qos-level).
905
906**System capability**: SystemCapability.Utils.Lang
907
908| Name| Value| Description|
909| -------- | -------- | -------- |
910| HIGH   | 0    | The task has a high priority.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
911| MEDIUM | 1 | The task has a medium priority.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
912| LOW | 2 | The task has a low priority.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
913| IDLE<sup>12+</sup> | 3 | The task is a background task.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
914
915**Example**
916
917```ts
918@Concurrent
919function printArgs(args: number): number {
920  let t: number = Date.now();
921  while (Date.now() - t < 1000) { // 1000: delay 1s
922    continue;
923  }
924  console.info("printArgs: " + args);
925  return args;
926}
927
928let allCount = 100; // 100: test number
929let taskArray: Array<taskpool.Task> = [];
930// Create 400 tasks and add them to taskArray.
931for (let i: number = 0; i < allCount; i++) {
932  let task1: taskpool.Task = new taskpool.Task(printArgs, i);
933  taskArray.push(task1);
934  let task2: taskpool.Task = new taskpool.Task(printArgs, i * 10); // 10: test number
935  taskArray.push(task2);
936  let task3: taskpool.Task = new taskpool.Task(printArgs, i * 100); // 100: test number
937  taskArray.push(task3);
938  let task4: taskpool.Task = new taskpool.Task(printArgs, i * 1000); // 1000: test number
939  taskArray.push(task4);
940}
941
942// Obtain different tasks from taskArray and specify different priorities for execution.
943for (let i: number = 0; i < taskArray.length; i+=4) { // 4: Four tasks are executed each time. When obtaining tasks cyclically, obtain the four items following the last batch to ensure that different tasks are obtained each time.
944  taskpool.execute(taskArray[i], taskpool.Priority.HIGH);
945  taskpool.execute(taskArray[i + 1], taskpool.Priority.LOW);
946  taskpool.execute(taskArray[i + 2], taskpool.Priority.MEDIUM);
947  taskpool.execute(taskArray[i + 3], taskpool.Priority.IDLE);
948}
949```
950
951## Task
952
953Implements a task. Before calling any APIs in **Task**, you must use [constructor](#constructor) to create a **Task** instance. A task can be executed for multiple times, placed in a task group, serial queue, or asynchronous queue for execution, or added with dependencies for execution.
954
955### Properties
956
957**System capability**: SystemCapability.Utils.Lang
958
959| Name                | Type      | Readable| Writable| Description                                                        |
960| -------------------- | --------- | ---- | ---- | ------------------------------------------------------------ |
961| 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).<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
962| arguments            | Object[]  | Yes  | Yes  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
963| name<sup>11+</sup>   | string    | Yes  | No  | Name of the task specified when the task is created.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
964| taskId<sup>18+</sup>   | number    | Yes  | No  | Task ID.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
965| totalDuration<sup>11+</sup>  | number    | Yes  | No  | Total execution time of the task. in ms.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
966| ioDuration<sup>11+</sup>     | number    | Yes  | No  | Asynchronous I/O time of the task. in ms.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
967| cpuDuration<sup>11+</sup>    | number    | Yes  | No  | CPU time of the task. in ms.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
968
969### constructor
970
971constructor(func: Function, ...args: Object[])
972
973A constructor used to create a **Task** instance.
974
975**System capability**: SystemCapability.Utils.Lang
976
977**Atomic service API**: This API can be used in atomic services since API version 11.
978
979**Parameters**
980
981| Name| Type     | Mandatory| Description                                                                 |
982| ------ | --------- | ---- | -------------------------------------------------------------------- |
983| func   | Function  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
984| 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**.|
985
986**Error codes**
987
988For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
989
990| ID| Error Message                                |
991| -------- | --------------------------------------- |
992| 401      | The input parameters are invalid. |
993| 10200014 | The function is not marked as concurrent. |
994
995**Example**
996
997```ts
998@Concurrent
999function printArgs(args: number): number {
1000  console.info("printArgs: " + args);
1001  return args;
1002}
1003
1004let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task");
1005```
1006
1007### constructor<sup>11+</sup>
1008
1009constructor(name: string, func: Function, ...args: Object[])
1010
1011A constructor used to create a **Task** instance, with the task name specified.
1012
1013**System capability**: SystemCapability.Utils.Lang
1014
1015**Atomic service API**: This API can be used in atomic services since API version 11.
1016
1017**Parameters**
1018
1019| Name| Type    | Mandatory| Description                                                        |
1020| ------ | -------- | ---- | ------------------------------------------------------------ |
1021| name   | string   | Yes  | Task name.                                                  |
1022| func   | Function  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
1023| 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**.|
1024
1025**Error codes**
1026
1027For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1028
1029| ID| Error Message                               |
1030| -------- | --------------------------------------- |
1031| 401      | The input parameters are invalid. |
1032| 10200014 | The function is not marked as concurrent. |
1033
1034**Example**
1035
1036```ts
1037@Concurrent
1038function printArgs(args: string): string {
1039  console.info("printArgs: " + args);
1040  return args;
1041}
1042
1043let taskName: string = "taskName";
1044let task: taskpool.Task = new taskpool.Task(taskName, printArgs, "this is my first Task");
1045let name: string = task.name;
1046```
1047
1048### isCanceled<sup>10+</sup>
1049
1050static isCanceled(): boolean
1051
1052Checks whether the running task is canceled. Before using this API, you must create a **Task** instance.
1053
1054**System capability**: SystemCapability.Utils.Lang
1055
1056**Atomic service API**: This API can be used in atomic services since API version 11.
1057
1058**Return value**
1059
1060| Type   | Description                                |
1061| ------- | ------------------------------------ |
1062| boolean | Returns **true** if the running task is canceled; returns **false** otherwise.|
1063
1064**Example**
1065
1066```ts
1067@Concurrent
1068function inspectStatus(arg: number): number {
1069    // do something
1070    if (taskpool.Task.isCanceled()) {
1071      console.info("task has been canceled.");
1072      // do something
1073      return arg + 1;
1074    }
1075    // do something
1076    return arg;
1077}
1078```
1079
1080> **NOTE**
1081>
1082> **isCanceled** must be used together with **taskpool.cancel**. If **cancel** is not called, **isCanceled** returns **false** by default.
1083
1084**Example**
1085
1086```ts
1087@Concurrent
1088function inspectStatus(arg: number): number {
1089  // Check whether the task has been canceled and respond accordingly.
1090  if (taskpool.Task.isCanceled()) {
1091    console.info("task has been canceled before 2s sleep.");
1092    return arg + 2;
1093  }
1094  // Wait for 2s.
1095  let t: number = Date.now();
1096  while (Date.now() - t < 2000) {
1097    continue;
1098  }
1099  // Check again whether the task has been canceled and respond accordingly.
1100  if (taskpool.Task.isCanceled()) {
1101    console.info("task has been canceled after 2s sleep.");
1102    return arg + 3;
1103  }
1104  return arg + 1;
1105}
1106
1107let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
1108taskpool.execute(task).then((res: Object)=>{
1109  console.info("taskpool test result: " + res);
1110}).catch((err: string) => {
1111  console.error("taskpool test occur error: " + err);
1112});
1113// If cancel is not called, isCanceled() returns false by default, and the task execution result is 101.
1114```
1115
1116### setTransferList<sup>10+</sup>
1117
1118setTransferList(transfer?: ArrayBuffer[]): void
1119
1120Sets the task transfer list. Before using this API, you must create a **Task** instance. If this API is not called, the ArrayBuffer in the data is transferred by default.
1121
1122> **NOTE**
1123>
1124> 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.
1125
1126**System capability**: SystemCapability.Utils.Lang
1127
1128**Atomic service API**: This API can be used in atomic services since API version 11.
1129
1130**Parameters**
1131
1132| Name  | Type          | Mandatory| Description                                         |
1133| -------- | ------------- | ---- | --------------------------------------------- |
1134| transfer | ArrayBuffer[] | No  | **ArrayBuffer** instance holding the objects to transfer. The default value is an empty array.|
1135
1136**Error codes**
1137
1138For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1139
1140| ID| Error Message                                                       |
1141| -------- | -------------------------------------------------------------- |
1142| 401      | Parameter error. Possible causes: 1. Incorrect parameter types; 2. Parameter verification failed. |
1143| 10200029 | An ArrayBuffer cannot be set as both a transfer list and a clone list. |
1144
1145**Example**
1146
1147```ts
1148@Concurrent
1149function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number {
1150  console.info("testTransfer arg1 byteLength: " + arg1.byteLength);
1151  console.info("testTransfer arg2 byteLength: " + arg2.byteLength);
1152  return 100;
1153}
1154
1155let buffer: ArrayBuffer = new ArrayBuffer(8);
1156let view: Uint8Array = new Uint8Array(buffer);
1157let buffer1: ArrayBuffer = new ArrayBuffer(16);
1158let view1: Uint8Array = new Uint8Array(buffer1);
1159
1160console.info("testTransfer view byteLength: " + view.byteLength);
1161console.info("testTransfer view1 byteLength: " + view1.byteLength);
1162// The execution result is as follows:
1163// testTransfer view byteLength: 8
1164// testTransfer view1 byteLength: 16
1165
1166let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1);
1167task.setTransferList([view.buffer, view1.buffer]);
1168taskpool.execute(task).then((res: Object)=>{
1169  console.info("test result: " + res);
1170}).catch((e: string)=>{
1171  console.error("test catch: " + e);
1172})
1173console.info("testTransfer view2 byteLength: " + view.byteLength);
1174console.info("testTransfer view3 byteLength: " + view1.byteLength);
1175// The value is 0 after transfer. The execution result is as follows:
1176// testTransfer view2 byteLength: 0
1177// testTransfer view3 byteLength: 0
1178```
1179
1180
1181### setCloneList<sup>11+</sup>
1182
1183setCloneList(cloneList: Object[] | ArrayBuffer[]): void
1184
1185Sets the task clone list. Before using this API, you must create a **Task** instance.
1186
1187> **NOTE**
1188>
1189> This API must be used together with the [@Sendable decorator](../../arkts-utils/arkts-sendable.md#sendable-decorator). Otherwise, an exception is thrown.
1190
1191**System capability**: SystemCapability.Utils.Lang
1192
1193**Atomic service API**: This API can be used in atomic services since API version 11.
1194
1195**Parameters**
1196
1197| Name   | Type                     | Mandatory| Description                                         |
1198| --------- | ------------------------ | ---- | --------------------------------------------- |
1199| cloneList | Object[] \| ArrayBuffer[]  | Yes| - The type of the passed-in array must be [sendable data types](../../arkts-utils/arkts-sendable.md#sendable-data-types) or ArrayBuffer.<br>- All [Sendable class](../../arkts-utils/arkts-sendable.md#sendable-class) instances or ArrayBuffer objects passed in to **cloneList** are transferred in copy mode between threads. This means that any modification to the destination objects does not affect the original objects.|
1200
1201**Error codes**
1202
1203For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1204
1205| ID| Error Message                                                       |
1206| -------- | -------------------------------------------------------------- |
1207| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1208| 10200029 | An ArrayBuffer cannot be set as both a transfer list and a clone list. |
1209
1210**Example**
1211
1212```ts
1213// sendable.ets
1214// Define two Sendable classes: BaseClass and its child class DeriveClass.
1215@Sendable
1216export class BaseClass {
1217  private str: string = "sendable: BaseClass";
1218  static num :number = 10;
1219  str1: string = "sendable: this is BaseClass's string";
1220  num1: number = 5;
1221  isDone1: boolean = false;
1222
1223  private fibonacciRecursive(n: number): number {
1224    if (n <= 1) {
1225      return n;
1226    } else {
1227      return this.fibonacciRecursive(n - 1) + this.fibonacciRecursive(n - 2);
1228    }
1229  }
1230
1231  private privateFunc(num: number): number{
1232    let res: number = this.fibonacciRecursive(num);
1233    console.info("sendable: BaseClass privateFunc res is: " + res);
1234    return res;
1235  }
1236
1237  publicFunc(num: number): number {
1238    return this.privateFunc(num);
1239  }
1240
1241  get GetNum(): number {
1242    return this.num1;
1243  }
1244  set SetNum(num: number) {
1245    this.num1 = num;
1246  }
1247
1248  constructor(){
1249    console.info(this.str);
1250    this.isDone1 = true;
1251  }
1252}
1253
1254@Sendable
1255export class DeriveClass extends BaseClass {
1256  name: string = "sendable: this is DeriveClass";
1257  printName() {
1258    console.info(this.name);
1259  }
1260  constructor() {
1261    super();
1262  }
1263}
1264```
1265
1266<!--code_no_check-->
1267```ts
1268// index.ets
1269// The host thread (UI main thread) calls the methods of BaseClass and DeriveClass in the task pool thread and accesses their properties.
1270import { taskpool } from '@kit.ArkTS'
1271import { BusinessError } from '@kit.BasicServicesKit'
1272import { BaseClass, DeriveClass } from './sendable'
1273
1274@Concurrent
1275function testFunc(arr: Array<BaseClass>, num: number): number {
1276  let baseInstance1 = arr[0];
1277  console.info("sendable: str1 is: " + baseInstance1.str1);
1278  baseInstance1.SetNum = 100;
1279  console.info("sendable: num1 is: " + baseInstance1.GetNum);
1280  console.info("sendable: isDone1 is: " + baseInstance1.isDone1);
1281  // Obtain the result of the item specified by num from Fibonacci sequence.
1282  let res: number = baseInstance1.publicFunc(num);
1283  return res;
1284}
1285
1286@Concurrent
1287function printLog(arr: Array<DeriveClass>): void {
1288  let deriveInstance = arr[0];
1289  deriveInstance.printName();
1290}
1291
1292@Entry
1293@Component
1294struct Index {
1295  @State message: string = 'Hello World'
1296
1297  build() {
1298    Row() {
1299      Column() {
1300        Text(this.message)
1301          .fontSize(50)
1302          .fontWeight(FontWeight.Bold)
1303        Button() {
1304          Text("TaskPool Test")
1305        }.onClick(() => {
1306          // task1 calls BaseClass.str1/BaseClass.SetNum/BaseClass.GetNum/BaseClass.isDone1/BaseClass.publicFunc.
1307          let baseInstance1: BaseClass = new BaseClass();
1308          let array1 = new Array<BaseClass>();
1309          array1.push(baseInstance1);
1310          let task1 = new taskpool.Task(testFunc, array1, 10);
1311          task1.setCloneList(array1);
1312          taskpool.execute(task1).then((res: Object) => {
1313            console.info("sendable: task1 res is: " + res);
1314          }).catch((e:BusinessError) => {
1315            console.error(`sendable: task1 execute Code is ${e.code}, message is ${e.message}`);
1316          })
1317
1318          // task2 calls DeriveClass.printName.
1319          let deriveInstance: DeriveClass = new DeriveClass();
1320          let array2 = new Array<DeriveClass>();
1321          array2.push(deriveInstance);
1322          let task2 = new taskpool.Task(printLog, array2);
1323          task2.setCloneList(array2);
1324          taskpool.execute(task2).then(() => {
1325            console.info("sendable: task2 execute success");
1326          }).catch((e:BusinessError) => {
1327            console.error(`sendable: task2 execute Code is ${e.code}, message is ${e.message}`);
1328          })
1329        })
1330        .height('15%')
1331        .width('30%')
1332      }
1333      .width('100%')
1334    }
1335    .height('100%')
1336  }
1337}
1338```
1339
1340
1341### sendData<sup>11+</sup>
1342
1343static sendData(...args: Object[]): void
1344
1345Sends data to the host thread and triggers the registered callback. Before using this API, you must create a **Task** instance.
1346
1347> **NOTE**
1348>
1349> - The API is called in the TaskPool thread.
1350> - Do not use this API in a callback function.
1351> - Before calling this API, ensure that the callback function for processing data has been registered in the host thread.
1352
1353**System capability**: SystemCapability.Utils.Lang
1354
1355**Atomic service API**: This API can be used in atomic services since API version 11.
1356
1357**Parameters**
1358
1359| Name  | Type         | Mandatory| Description                                             |
1360| -------- | ------------- | ---- | ------------------------------------------------- |
1361| args     | Object[]      | No  | 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). The default value is **undefined**.|
1362
1363**Error codes**
1364
1365For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1366
1367| ID| Error Message                                |
1368| -------- | --------------------------------------- |
1369| 401       | The input parameters are invalid. |
1370| 10200006  | An exception occurred during serialization. |
1371| 10200022  | The function is not called in the TaskPool thread. |
1372| 10200023  | The function is not called in the concurrent function. |
1373| 10200024  | The callback is not registered on the host side. |
1374
1375**Example**
1376
1377```ts
1378@Concurrent
1379function sendDataTest(num: number): number {
1380  let res: number = num * 10;
1381  taskpool.Task.sendData(res);
1382  return num;
1383}
1384
1385function printLog(data: number): void {
1386  console.info("taskpool: data is: " + data);
1387}
1388
1389async function taskpoolTest(): Promise<void> {
1390  try {
1391    let task: taskpool.Task = new taskpool.Task(sendDataTest, 1);
1392    task.onReceiveData(printLog);
1393    await taskpool.execute(task);
1394  } catch (e) {
1395    console.error(`taskpool: error code: ${e.code}, info: ${e.message}`);
1396  }
1397}
1398
1399taskpoolTest();
1400```
1401
1402
1403### onReceiveData<sup>11+</sup>
1404
1405onReceiveData(callback?: Function): void
1406
1407Registers a callback for a task to receive and process data from the worker thread. Before using this API, you must create a **Task** instance.
1408
1409> **NOTE**
1410>
1411> If multiple callbacks are registered for the same task, only the last registration takes effect.
1412
1413**System capability**: SystemCapability.Utils.Lang
1414
1415**Atomic service API**: This API can be used in atomic services since API version 11.
1416
1417**Parameters**
1418
1419| Name  | Type    | Mandatory| Description                                                        |
1420| -------- | -------- | ---- | ------------------------------------------------------------ |
1421| 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.|
1422
1423**Error codes**
1424
1425For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1426
1427| ID| Error Message|
1428| -------- | -------- |
1429| 401 | Parameter error. Possible causes: 1. Incorrect parameter types; 2. Parameter verification failed. |
1430
1431**Example**
1432
1433```ts
1434@Concurrent
1435function ConcurrentFunc(num: number): number {
1436  let res: number = num * 10;
1437  taskpool.Task.sendData(res);
1438  return num;
1439}
1440
1441function printLog(data: number): void {
1442  console.info("taskpool: data is: " + data);
1443}
1444
1445async function testFunc(): Promise<void> {
1446  try {
1447    let task: taskpool.Task = new taskpool.Task(ConcurrentFunc, 1);
1448    task.onReceiveData(printLog);
1449    await taskpool.execute(task);
1450  } catch (e) {
1451    console.error(`taskpool: error code: ${e.code}, info: ${e.message}`);
1452  }
1453}
1454
1455testFunc();
1456```
1457
1458### addDependency<sup>11+</sup>
1459
1460addDependency(...tasks: Task[]): void
1461
1462Adds dependent tasks for this task. Before using this API, you must create a **Task** instance. The task and its dependent tasks cannot be a task in a task group, serial queue, or asynchronous queue, a task that has been executed, or a periodic task. A task with a dependency relationship (a task that depends on another task or a task that is depended on) cannot be executed multiple times.
1463
1464**System capability**: SystemCapability.Utils.Lang
1465
1466**Atomic service API**: This API can be used in atomic services since API version 11.
1467
1468**Parameters**
1469
1470| Name| Type            | Mandatory| Description              |
1471| ------ | --------------- | ---- | ------------------ |
1472| tasks  | [Task](#task)[] | No  | Array of tasks on which the current task depends. The default value is **undefined**.|
1473
1474**Error codes**
1475
1476For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1477
1478| ID| Error Message                       |
1479| -------- | ------------------------------- |
1480| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1481| 10200026 | There is a circular dependency. |
1482| 10200052 | The periodic task cannot have a dependency. |
1483| 10200056 | The task has been executed by the AsyncRunner. |
1484
1485**Example**
1486
1487```ts
1488@Concurrent
1489function delay(args: number): number {
1490  let t: number = Date.now();
1491  while ((Date.now() - t) < 1000) {
1492	continue;
1493  }
1494  return args;
1495}
1496
1497let task1:taskpool.Task = new taskpool.Task(delay, 100);
1498let task2:taskpool.Task = new taskpool.Task(delay, 200);
1499let task3:taskpool.Task = new taskpool.Task(delay, 200);
1500
1501console.info("dependency: add dependency start");
1502task1.addDependency(task2);
1503task2.addDependency(task3);
1504console.info("dependency: add dependency end");
1505
1506console.info("dependency: start execute second")
1507taskpool.execute(task1).then(() => {
1508  console.info("dependency: second task1 success");
1509})
1510taskpool.execute(task2).then(() => {
1511  console.info("dependency: second task2 success");
1512})
1513taskpool.execute(task3).then(() => {
1514  console.info("dependency: second task3 success");
1515})
1516```
1517
1518### removeDependency<sup>11+</sup>
1519
1520removeDependency(...tasks: Task[]): void
1521
1522Removes dependent tasks for this task. Before using this API, you must create a **Task** instance.
1523
1524**System capability**: SystemCapability.Utils.Lang
1525
1526**Atomic service API**: This API can be used in atomic services since API version 11.
1527
1528**Parameters**
1529
1530| Name| Type  | Mandatory| Description              |
1531| ------ | ------ | ---- | ------------------ |
1532| tasks  | [Task](#task)[] | No  | Array of tasks on which the current task depends. The default value is **undefined**.|
1533
1534**Error codes**
1535
1536For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1537
1538| ID| Error Message                      |
1539| -------- | ------------------------------ |
1540| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1541| 10200027 | The dependency does not exist. |
1542| 10200052 | The periodic task cannot have a dependency. |
1543| 10200056 | The task has been executed by the AsyncRunner. |
1544
1545**Example**
1546
1547```ts
1548@Concurrent
1549function delay(args: number): number {
1550  let t: number = Date.now();
1551  while ((Date.now() - t) < 1000) {
1552	continue;
1553  }
1554  return args;
1555}
1556
1557let task1:taskpool.Task = new taskpool.Task(delay, 100);
1558let task2:taskpool.Task = new taskpool.Task(delay, 200);
1559let task3:taskpool.Task = new taskpool.Task(delay, 200);
1560
1561console.info("dependency: add dependency start");
1562task1.addDependency(task2);
1563task2.addDependency(task3);
1564console.info("dependency: add dependency end");
1565console.info("dependency: remove dependency start");
1566task1.removeDependency(task2);
1567task2.removeDependency(task3);
1568console.info("dependency: remove dependency end");
1569
1570console.info("dependency: start execute")
1571taskpool.execute(task1).then(() => {
1572  console.info("dependency: task1 success");
1573})
1574taskpool.execute(task2).then(() => {
1575  console.info("dependency: task2 success");
1576})
1577taskpool.execute(task3).then(() => {
1578  console.info("dependency: task3 success");
1579})
1580```
1581
1582
1583### onEnqueued<sup>12+</sup>
1584
1585onEnqueued(callback: CallbackFunction): void
1586
1587Registers a callback function and calls it when a task is enqueued. The registration must be carried out before the task is executed. Otherwise, an exception is thrown.
1588
1589**System capability**: SystemCapability.Utils.Lang
1590
1591**Atomic service API**: This API can be used in atomic services since API version 12.
1592
1593**Parameters**
1594
1595| Name| Type  | Mandatory| Description              |
1596| ------ | ------ | ---- | ------------------ |
1597| callback  | [CallbackFunction](#callbackfunction12) | Yes  | Callback function to register.|
1598
1599**Error codes**
1600
1601For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1602
1603| ID| Error Message                      |
1604| -------- | ------------------------------ |
1605| 401       | The input parameters are invalid. |
1606| 10200034  | The executed task does not support the registration of listeners. |
1607
1608**Example**
1609
1610```ts
1611import { taskpool } from '@kit.ArkTS'
1612
1613@Concurrent
1614function delay(args: number): number {
1615  let t: number = Date.now();
1616  while ((Date.now() - t) < 1000) {
1617	continue;
1618  }
1619  return args;
1620}
1621
1622let task: taskpool.Task = new taskpool.Task(delay, 1);
1623task.onEnqueued(()=>{
1624  console.info("taskpool: onEnqueued")
1625});
1626taskpool.execute(task).then(()=> {
1627  console.info("taskpool: execute task success")
1628});
1629```
1630
1631
1632### onStartExecution<sup>12+</sup>
1633
1634onStartExecution(callback: CallbackFunction): void
1635
1636Registers a callback function and calls it when the execution of a task starts. The registration must be carried out before the task is executed. Otherwise, an exception is thrown.
1637
1638**System capability**: SystemCapability.Utils.Lang
1639
1640**Atomic service API**: This API can be used in atomic services since API version 12.
1641
1642**Parameters**
1643
1644| Name| Type  | Mandatory| Description              |
1645| ------ | ------ | ---- | ------------------ |
1646| callback  | [CallbackFunction](#callbackfunction12)  | Yes  | Callback function to register.|
1647
1648**Error codes**
1649
1650For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1651
1652| ID| Error Message                      |
1653| -------- | ------------------------------ |
1654| 401       | The input parameters are invalid. |
1655| 10200034  | The executed task does not support the registration of listeners. |
1656
1657**Example**
1658
1659```ts
1660import { taskpool } from '@kit.ArkTS'
1661
1662@Concurrent
1663function delay(args: number): number {
1664  let t: number = Date.now();
1665  while ((Date.now() - t) < 1000) {
1666	continue;
1667  }
1668  return args;
1669}
1670
1671let task: taskpool.Task = new taskpool.Task(delay, 1);
1672task.onStartExecution(()=>{
1673  console.info("taskpool: onStartExecution")
1674});
1675taskpool.execute(task).then(()=> {
1676  console.info("taskpool: execute task success")
1677});
1678```
1679
1680### onExecutionFailed<sup>12+</sup>
1681
1682onExecutionFailed(callback: CallbackFunctionWithError): void
1683
1684Registers a callback function and calls it when a task fails to be enqueued. The registration must be carried out before the task is executed. Otherwise, an exception is thrown.
1685
1686**System capability**: SystemCapability.Utils.Lang
1687
1688**Atomic service API**: This API can be used in atomic services since API version 12.
1689
1690**Parameters**
1691
1692| Name| Type  | Mandatory| Description              |
1693| ------ | ------ | ---- | ------------------ |
1694| callback  | [CallbackFunctionWithError](#callbackfunctionwitherror12)  | Yes  | Callback function to register.|
1695
1696**Error codes**
1697
1698For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1699
1700| ID| Error Message                      |
1701| -------- | ------------------------------ |
1702| 401       | The input parameters are invalid. |
1703| 10200034  | The executed task does not support the registration of listeners. |
1704
1705**Example**
1706
1707```ts
1708import { taskpool } from '@kit.ArkTS'
1709import { BusinessError } from '@kit.BasicServicesKit'
1710import { HashMap } from '@kit.ArkTS'
1711
1712@Concurrent
1713function test(args:number) {
1714  let t = Date.now()
1715  while ((Date.now() - t) < 100) {
1716    continue;
1717  }
1718  let hashMap1: HashMap<string, number> = new HashMap();
1719  hashMap1.set('a', args);
1720  return hashMap1;
1721}
1722
1723let task2 = new taskpool.Task(test, 1);
1724task2.onExecutionFailed((e:Error)=>{
1725  console.info("taskpool: onExecutionFailed error is " + e);
1726})
1727taskpool.execute(task2).then(()=>{
1728  console.info("taskpool: execute task success")
1729}).catch((e:BusinessError)=>{
1730  console.error(`taskpool: error code: ${e.code}, error info: ${e.message}`);
1731})
1732```
1733
1734### onExecutionSucceeded<sup>12+</sup>
1735
1736onExecutionSucceeded(callback: CallbackFunction): void
1737
1738Registers a callback function and calls it when a task is executed successfully. The registration must be carried out before the task is executed. Otherwise, an exception is thrown.
1739
1740**System capability**: SystemCapability.Utils.Lang
1741
1742**Atomic service API**: This API can be used in atomic services since API version 12.
1743
1744**Parameters**
1745
1746| Name| Type  | Mandatory| Description              |
1747| ------ | ------ | ---- | ------------------ |
1748| callback  | [CallbackFunction](#callbackfunction12)  | Yes  | Callback function to register.|
1749
1750**Error codes**
1751
1752For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1753
1754| ID| Error Message                      |
1755| -------- | ------------------------------ |
1756| 401       | The input parameters are invalid. |
1757| 10200034  | The executed task does not support the registration of listeners. |
1758
1759**Example**
1760
1761```ts
1762import { taskpool } from '@kit.ArkTS'
1763
1764@Concurrent
1765function delay(args: number): number {
1766  let t: number = Date.now();
1767  while ((Date.now() - t) < 1000) {
1768	  continue;
1769  }
1770  return args;
1771}
1772
1773let task: taskpool.Task = new taskpool.Task(delay, 1);
1774task.onExecutionSucceeded(()=>{
1775  console.info("taskpool: onExecutionSucceeded")
1776});
1777taskpool.execute(task).then(()=> {
1778  console.info("taskpool: execute task success")
1779});
1780```
1781
1782### isDone<sup>12+</sup>
1783
1784isDone(): boolean
1785
1786Checks whether the task is complete.
1787
1788**System capability**: SystemCapability.Utils.Lang
1789
1790**Atomic service API**: This API can be used in atomic services since API version 12.
1791
1792**Return value**
1793
1794| Type   | Description                                |
1795| ------- | ------------------------------------ |
1796| boolean | Check result. The value **true** means that the task is complete, and **false** means the opposite.|
1797
1798**Example**
1799
1800```ts
1801@Concurrent
1802function inspectStatus(arg: number): number {
1803  // 2s sleep
1804  let t: number = Date.now();
1805  while (Date.now() - t < 1000) {
1806    continue;
1807  }
1808  return arg + 1;
1809}
1810
1811async function taskpoolCancel(): Promise<void> {
1812  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
1813  taskpool.execute(task).then((res: Object)=>{
1814    console.info("taskpool test result: " + res);
1815  }).catch((err: string) => {
1816    console.error("taskpool test occur error: " + err);
1817  });
1818
1819  setTimeout(()=>{
1820    if (!task.isDone()) {
1821      taskpool.cancel(task);
1822    }
1823  }, 3000); // Wait for 3s to ensure that the task has been executed.
1824}
1825
1826taskpoolCancel();
1827```
1828
1829## CallbackFunction<sup>12+</sup>
1830
1831type CallbackFunction = () => void
1832
1833Describes a callback function.
1834
1835**System capability**: SystemCapability.Utils.Lang
1836
1837**Atomic service API**: This API can be used in atomic services since API version 12.
1838
1839
1840## CallbackFunctionWithError<sup>12+</sup>
1841
1842type CallbackFunctionWithError = (e: Error) => void
1843
1844Describes a callback function with an error message.
1845
1846**System capability**: SystemCapability.Utils.Lang
1847
1848**Atomic service API**: This API can be used in atomic services since API version 12.
1849
1850**Parameters**
1851
1852| Name| Type  | Mandatory| Description              |
1853| ------ | ------ | ---- | ------------------ |
1854| e  | Error | Yes  | Error message.|
1855
1856
1857## LongTask<sup>12+</sup>
1858
1859**System capability**: SystemCapability.Utils.Lang
1860
1861Describes a continuous task. **LongTask** inherits from [Task](#task).
1862No upper limit is set for the execution time of a continuous task, and no timeout exception is thrown if a continuous task runs for a long period of time. However, a continuous task cannot be executed in a task group or executed for multiple times.
1863The thread for executing a continuous task exists until [terminateTask](#taskpoolterminatetask12) is called after the execution is complete. The thread is reclaimed when it is idle.
1864
1865**Example**
1866
1867```ts
1868@Concurrent
1869function printArgs(args: string): string {
1870  console.info("printArgs: " + args);
1871  return args;
1872}
1873
1874let task: taskpool.LongTask = new taskpool.LongTask(printArgs, "this is my first LongTask");
1875```
1876
1877
1878## GenericsTask<sup>13+</sup>
1879
1880**System capability**: SystemCapability.Utils.Lang
1881
1882Implements a generic task. **GenericsTask** inherits from [Task](#task).
1883During the creation of a generic task, the passed-in parameter types and return value types of concurrent functions are verified in the compilation phase. Other behaviors are the same as those during the creation of a task.
1884
1885### constructor<sup>13+</sup>
1886
1887constructor(func: (...args: A) => R | Promise\<R>, ...args: A)
1888
1889A constructor used to create a **GenericsTask** object.
1890
1891**System capability**: SystemCapability.Utils.Lang
1892
1893**Atomic service API**: This API can be used in atomic services since API version 13.
1894
1895**Parameters**
1896
1897| Name| Type     | Mandatory| Description                                                                 |
1898| ------ | --------- | ---- | -------------------------------------------------------------------- |
1899| func   | (...args: A) => R \| Promise\<R>  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
1900| args   | A | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
1901
1902**Error codes**
1903
1904For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1905
1906| ID| Error Message                                |
1907| -------- | --------------------------------------- |
1908| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
1909| 10200014 | The function is not marked as concurrent. |
1910
1911**Example**
1912
1913```ts
1914@Concurrent
1915function printArgs(args: string): string {
1916  console.info("printArgs: " + args);
1917  return args;
1918}
1919
1920@Concurrent
1921function testWithThreeParams(a: number, b: string, c: number): string {
1922  return b;
1923}
1924
1925@Concurrent
1926function testWithArray(args: [number, string]): string {
1927  return "success";
1928}
1929
1930let task1: taskpool.Task = new taskpool.GenericsTask<[string], string>(printArgs, "this is my first LongTask");
1931
1932let task2: taskpool.Task = new taskpool.GenericsTask<[number, string, number], string>(testWithThreeParams, 100, "test", 100);
1933
1934let task3: taskpool.Task = new taskpool.GenericsTask<[[number, string]], string>(testWithArray, [100, "test"]);
1935```
1936
1937### constructor<sup>13+</sup>
1938
1939constructor(name: string, func: (...args: A) => R | Promise\<R>, ...args: A)
1940
1941A constructor used to create a **GenericsTask** instance, with the task name specified.
1942
1943**System capability**: SystemCapability.Utils.Lang
1944
1945**Atomic service API**: This API can be used in atomic services since API version 13.
1946
1947**Parameters**
1948
1949| Name| Type    | Mandatory| Description                                                        |
1950| ------ | -------- | ---- | ------------------------------------------------------------ |
1951| name   | string   | Yes  | Name of the generic task.                                                  |
1952| func   | (...args: A) => R \| Promise\<R>  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
1953| args   | A | No  | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.|
1954
1955**Error codes**
1956
1957For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1958
1959| ID| Error Message                               |
1960| -------- | --------------------------------------- |
1961| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
1962| 10200014 | The function is not marked as concurrent. |
1963
1964**Example**
1965
1966```ts
1967@Concurrent
1968function printArgs(args: string): string {
1969  console.info("printArgs: " + args);
1970  return args;
1971}
1972
1973let taskName: string = "taskName";
1974let task: taskpool.Task = new taskpool.GenericsTask<[string], string>(taskName, printArgs, "this is my first Task");
1975let name: string = task.name;
1976```
1977
1978## TaskGroup<sup>10+</sup>
1979
1980Implements a task group, in which tasks are associated with each other and 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. If multiple tasks in the task group fail, the exception of the first failed task 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.
1981
1982### constructor<sup>10+</sup>
1983
1984constructor()
1985
1986Constructor used to create a **TaskGroup** instance.
1987
1988**System capability**: SystemCapability.Utils.Lang
1989
1990**Atomic service API**: This API can be used in atomic services since API version 11.
1991
1992**Example**
1993
1994```ts
1995let taskGroup = new taskpool.TaskGroup();
1996```
1997
1998### constructor<sup>11+</sup>
1999
2000constructor(name: string)
2001
2002A constructor used to create a **TaskGroup** instance, with the task group name specified.
2003
2004**System capability**: SystemCapability.Utils.Lang
2005
2006**Atomic service API**: This API can be used in atomic services since API version 11.
2007
2008**Parameters**
2009
2010| Name| Type  | Mandatory| Description        |
2011| ------ | ------ | ---- | ------------ |
2012| name   | string | Yes  | Task group name.|
2013
2014**Error codes**
2015
2016For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2017
2018| ID| Error Message|
2019| -------- | -------- |
2020| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2021
2022**Example**
2023
2024```ts
2025let taskGroupName: string = "groupName";
2026let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(taskGroupName);
2027let name: string = taskGroup.name;
2028```
2029
2030### addTask<sup>10+</sup>
2031
2032addTask(func: Function, ...args: Object[]): void
2033
2034Adds the function to be executed to this task group. Before using this API, you must create a **TaskGroup** instance.
2035
2036**System capability**: SystemCapability.Utils.Lang
2037
2038**Atomic service API**: This API can be used in atomic services since API version 11.
2039
2040**Parameters**
2041
2042| Name| Type     | Mandatory| Description                                                                  |
2043| ------ | --------- | ---- | ---------------------------------------------------------------------- |
2044| func   | Function  | Yes  | Function to be executed. The function must be decorated using [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator). For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).    |
2045| 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**.|
2046
2047**Error codes**
2048
2049For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
2050
2051| ID| Error Message                                |
2052| -------- | --------------------------------------- |
2053| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2054| 10200014 | The function is not marked as concurrent. |
2055
2056**Example**
2057
2058```ts
2059@Concurrent
2060function printArgs(args: number): number {
2061  console.info("printArgs: " + args);
2062  return args;
2063}
2064
2065let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
2066taskGroup.addTask(printArgs, 100); // 100: test number
2067```
2068
2069### addTask<sup>10+</sup>
2070
2071addTask(task: Task): void
2072
2073Adds a created task to this task group. Before using this API, you must create a **TaskGroup** instance. Tasks in another task group, serial queue, or asynchronous queue, dependent tasks, continuous tasks, tasks that have been executed, and periodic tasks cannot be added to the task group.
2074
2075**System capability**: SystemCapability.Utils.Lang
2076
2077**Atomic service API**: This API can be used in atomic services since API version 11.
2078
2079**Parameters**
2080
2081| Name  | Type                 | Mandatory| Description                                      |
2082| -------- | --------------------- | ---- | ---------------------------------------- |
2083| task     | [Task](#task)         | Yes  | Task to be added to the task group.                 |
2084
2085**Error codes**
2086
2087For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
2088
2089| ID| Error Message                                |
2090| -------- | --------------------------------------- |
2091| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
2092| 10200014 | The function is not marked as concurrent. |
2093| 10200051 | The periodic task cannot be executed again.  |
2094| 10200057 | The task cannot be executed by two APIs.  |
2095
2096**Example**
2097
2098```ts
2099@Concurrent
2100function printArgs(args: number): number {
2101  console.info("printArgs: " + args);
2102  return args;
2103}
2104
2105let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
2106let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
2107taskGroup.addTask(task);
2108```
2109
2110### Properties
2111
2112**System capability**: SystemCapability.Utils.Lang
2113
2114**Atomic service API**: This API can be used in atomic services since API version 11.
2115
2116| Name| Type  | Readable| Writable| Description                        |
2117| ---- | ------ | ---- | ---- | ---------------------------- |
2118| name<sup>11+</sup> | string | Yes  | Yes  | Name of the task group specified when the task group is created.|
2119
2120## SequenceRunner <sup>11+</sup>
2121
2122Implements a serial queue, in which all tasks are executed in sequence. Before calling any APIs in **SequenceRunner**, you must use [constructor](#constructor11-3) to create a **SequenceRunner** instance.
2123
2124### constructor<sup>11+</sup>
2125
2126constructor(priority?: Priority)
2127
2128A constructor used to create a **SequenceRunner** instance.
2129
2130**System capability**: SystemCapability.Utils.Lang
2131
2132**Atomic service API**: This API can be used in atomic services since API version 11.
2133
2134**Parameters**
2135
2136| Name  | Type                 | Mandatory| Description                                                      |
2137| -------- | --------------------- | ---- | ---------------------------------------------------------- |
2138| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
2139
2140**Error codes**
2141
2142For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2143
2144| ID| Error Message|
2145| -------- | -------- |
2146| 401 | Parameter error. Possible causes: 1. Incorrect parameter types; 2. Parameter verification failed. |
2147
2148**Example**
2149
2150```ts
2151let runner: taskpool.SequenceRunner = new taskpool.SequenceRunner();
2152```
2153
2154### constructor<sup>12+</sup>
2155
2156constructor(name: string, priority?: Priority)
2157
2158A constructor used to create a **SequenceRunner** instance. This instance represents a global serial queue. If the passed-in name is the same as an existing name, the same serial queue is returned.
2159
2160> **NOTE**
2161>
2162> - The bottom layer uses the singleton mode to ensure that the same instance is obtained when a serial queue with the same name is created.
2163> - The priority of a serial queue cannot be modified.
2164
2165**System capability**: SystemCapability.Utils.Lang
2166
2167**Atomic service API**: This API can be used in atomic services since API version 12.
2168
2169**Parameters**
2170
2171| Name  | Type                 | Mandatory| Description                                                      |
2172| -------- | --------------------- | ---- | ---------------------------------------------------------- |
2173| name     | string                | Yes  | Name of a serial queue.|
2174| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
2175
2176**Error codes**
2177
2178For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2179
2180| ID| Error Message|
2181| -------- | -------- |
2182| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
2183
2184**Example**
2185
2186```ts
2187let runner:taskpool.SequenceRunner = new taskpool.SequenceRunner("runner1", taskpool.Priority.LOW);
2188```
2189
2190### execute<sup>11+</sup>
2191
2192execute(task: Task): Promise\<Object>
2193
2194Adds a task to the serial queue for execution. Before using this API, you must create a **SequenceRunner** instance. Tasks in another task group, serial queue, or asynchronous queue, dependent tasks, and tasks that have been executed cannot be added to the serial queue.
2195
2196> **NOTE**
2197>
2198> - Tasks that depend others cannot be added to the serial queue.
2199> - The failure or cancellation of a task does not affect the execution of subsequent tasks in the serial queue.
2200
2201**System capability**: SystemCapability.Utils.Lang
2202
2203**Atomic service API**: This API can be used in atomic services since API version 11.
2204
2205**Parameters**
2206
2207| Name| Type         | Mandatory| Description                            |
2208| ------ | ------------- | ---- | -------------------------------- |
2209| task   | [Task](#task) | Yes  | Task to be added to the serial queue.|
2210
2211**Return value**
2212
2213| Type            | Description                             |
2214| ---------------- | --------------------------------- |
2215| Promise\<Object> | Promise used to return the task execution result.|
2216
2217**Error codes**
2218
2219For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
2220
2221| ID| Error Message                                   |
2222| -------- | ------------------------------------------- |
2223| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
2224| 10200006 | An exception occurred during serialization. |
2225| 10200025 | dependent task not allowed.  |
2226| 10200051 | The periodic task cannot be executed again.  |
2227| 10200057 | The task cannot be executed by two APIs.  |
2228
2229**Example**
2230
2231```ts
2232@Concurrent
2233function additionDelay(delay:number): void {
2234  let start: number = new Date().getTime();
2235  while (new Date().getTime() - start < delay) {
2236    continue;
2237  }
2238}
2239@Concurrent
2240function waitForRunner(finalString: string): string {
2241  return finalString;
2242}
2243async function seqRunner()
2244{
2245  let finalString:string = "";
2246  let task1:taskpool.Task = new taskpool.Task(additionDelay, 3000);
2247  let task2:taskpool.Task = new taskpool.Task(additionDelay, 2000);
2248  let task3:taskpool.Task = new taskpool.Task(additionDelay, 1000);
2249  let task4:taskpool.Task = new taskpool.Task(waitForRunner, finalString);
2250
2251  let runner:taskpool.SequenceRunner = new taskpool.SequenceRunner();
2252  runner.execute(task1).then(() => {
2253    finalString += 'a';
2254    console.info("seqrunner: task1 done.");
2255  });
2256  runner.execute(task2).then(() => {
2257    finalString += 'b';
2258    console.info("seqrunner: task2 done");
2259  });
2260  runner.execute(task3).then(() => {
2261    finalString += 'c';
2262    console.info("seqrunner: task3 done");
2263  });
2264  await runner.execute(task4);
2265  console.info("seqrunner: task4 done, finalString is " + finalString);
2266}
2267```
2268
2269## AsyncRunner<sup>18+</sup>
2270
2271Implements an asynchronous queue, for which you can specify the task execution concurrency and queuing policy. Before calling any APIs in **AsyncRunner**, you must use [constructor](#constructor18) to create an **AsyncRunner** instance.
2272
2273### constructor<sup>18+</sup>
2274
2275constructor(runningCapacity: number, waitingCapacity?: number)
2276
2277A constructor used to create an **AsyncRunner** instance. It constructs a non-global asynchronous queue. Even when the parameters passed are the same, it returns different asynchronous queues.
2278
2279**System capability**: SystemCapability.Utils.Lang
2280
2281**Atomic service API**: This API can be used in atomic services since API version 18.
2282
2283**Parameters**
2284
2285| Name  | Type                 | Mandatory| Description                                                      |
2286| -------- | --------------------- | ---- | ---------------------------------------------------------- |
2287| runningCapacity | number | Yes  | Maximum number of tasks that can run concurrently. The value must be a positive integer. If a negative number is passed, an error is reported. If a non-integer is passed, the value is rounded down.|
2288| waitingCapacity | number | No  | Maximum number of tasks that can be queued. The value must be greater than or equal to 0. If a negative number is passed, an error is reported. If a non-integer is passed, the value is rounded down. The default value is 0, indicating that there is no limit to the number of tasks that can wait. If a value greater than 0 is passed, tasks will be discarded from the front of the queue once the queue size exceeds this limit, implementing a discard policy.|
2289
2290**Error codes**
2291
2292For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2293
2294| ID| Error Message|
2295| -------- | -------- |
2296| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
2297
2298**Example**
2299
2300```ts
2301let runner: taskpool.AsyncRunner = new taskpool.AsyncRunner(5);
2302```
2303
2304### constructor<sup>18+</sup>
2305
2306constructor(name: string, runningCapacity: number, waitingCapacity?: number)
2307
2308A constructor used to create an **AsyncRunner** instance. It constructs a global asynchronous queue. If the passed-in name is the same as an existing name, the same asynchronous queue is returned.
2309
2310> **NOTE**
2311>
2312> - The bottom layer uses the singleton mode to ensure that the same instance is obtained when an asynchronous queue with the same name is created.
2313> - The task execution concurrency and waiting capacity cannot be modified.
2314
2315**System capability**: SystemCapability.Utils.Lang
2316
2317**Atomic service API**: This API can be used in atomic services since API version 18.
2318
2319**Parameters**
2320
2321| Name  | Type                 | Mandatory| Description                                                      |
2322| -------- | --------------------- | ---- | ---------------------------------------------------------- |
2323| name     | string                | Yes  | Name of an asynchronous queue.|
2324| runningCapacity | number | Yes  | Maximum number of tasks that can run concurrently. The value must be a positive integer. If a negative number is passed, an error is reported. If a non-integer is passed, the value is rounded down.|
2325| waitingCapacity | number | No  | Maximum number of tasks that can be queued. The value must be greater than or equal to 0. If a negative number is passed, an error is reported. If a non-integer is passed, the value is rounded down. The default value is 0, indicating that there is no limit to the number of tasks that can wait. If a value greater than 0 is passed, tasks will be discarded from the front of the queue once the queue size exceeds this limit, implementing a discard policy.|
2326
2327**Error codes**
2328
2329For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2330
2331| ID| Error Message|
2332| -------- | -------- |
2333| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
2334
2335**Example**
2336
2337```ts
2338let runner:taskpool.AsyncRunner = new taskpool.AsyncRunner("runner1", 5, 5);
2339```
2340
2341### execute<sup>18+</sup>
2342
2343execute(task: Task, priority?: Priority): Promise\<Object>
2344
2345Adds a task to the asynchronous queue for execution. Before using this API, you must create an **AsyncRunner** instance.
2346
2347> **NOTE**
2348>
2349> - Tasks in a task group cannot be added to the asynchronous queue.
2350> - Tasks in a serial queue cannot be added to the asynchronous queue.
2351> - Tasks in other asynchronous queues cannot be added to the asynchronous queue.
2352> - Periodic tasks cannot be added to the asynchronous queue.
2353> - Delayed tasks cannot be added to the asynchronous queue.
2354> - Tasks that depend others cannot be added to the asynchronous queue.
2355> - Tasks that have been executed cannot be added to the asynchronous queue.
2356
2357**System capability**: SystemCapability.Utils.Lang
2358
2359**Atomic service API**: This API can be used in atomic services since API version 18.
2360
2361**Parameters**
2362
2363| Name| Type         | Mandatory| Description                            |
2364| ------ | ------------- | ---- | -------------------------------- |
2365| task   | [Task](#task) | Yes  | Task to be added to the asynchronous queue.|
2366| priority | [Priority](#priority) | No  | Priority of the task. The default value is **taskpool.Priority.MEDIUM**.|
2367
2368**Return value**
2369
2370| Type            | Description                             |
2371| ---------------- | --------------------------------- |
2372| Promise\<Object> | Promise used to return the task execution result.|
2373
2374**Error codes**
2375
2376For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
2377
2378| ID| Error Message                                   |
2379| -------- | ------------------------------------------- |
2380| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
2381| 10200006 | An exception occurred during serialization. |
2382| 10200025 | dependent task not allowed.  |
2383| 10200051 | The periodic task cannot be executed again.  |
2384| 10200054 | The asyncRunner task is discarded.  |
2385| 10200057 | The task cannot be executed by two APIs.  |
2386
2387**Example**
2388
2389```ts
2390@Concurrent
2391function additionDelay(delay:number): void {
2392  let start: number = new Date().getTime();
2393  while (new Date().getTime() - start < delay) {
2394    continue;
2395  }
2396}
2397async function asyRunner()
2398{
2399  let runner:taskpool.AsyncRunner = new taskpool.AsyncRunner("runner1", 5, 5);
2400  for (let i = 0; i < 30; i++) {
2401    let task:taskpool.Task = new taskpool.Task(additionDelay, 1000);
2402    runner.execute(task).then(() => {
2403      console.info("asyncRunner: task" + i + " done.");
2404    }).catch((e: BusinessError) => {
2405      console.info("asyncRunner: task" + i + " error." + e.code + "-" + e.message);
2406    });
2407  }
2408}
2409
2410async function asyRunner2()
2411{
2412  let runner:taskpool.AsyncRunner = new taskpool.AsyncRunner(5);
2413  for (let i = 0; i < 20; i++) {
2414    let task:taskpool.Task = new taskpool.Task(additionDelay, 1000);
2415    runner.execute(task).then(() => {
2416      console.info("asyncRunner: task" + i + " done.");
2417    });
2418  }
2419}
2420```
2421
2422## State<sup>10+</sup>
2423
2424Enumerates the task states. After a task is created and **execute()** is called, the task is placed in the internal queue of the task pool and the state is **WAITING**. When the task is being executed by the worker thread of the task pool, the state changes to **RUNNING**. After the task is executed and the result is returned, the state is reset to **WAITING**. When the task is proactively canceled, the state changes to **CANCELED**.
2425
2426**System capability**: SystemCapability.Utils.Lang
2427
2428**Atomic service API**: This API can be used in atomic services since API version 11.
2429
2430| Name     | Value       | Description         |
2431| --------- | -------- | ------------- |
2432| WAITING   | 1        | The task is waiting.|
2433| RUNNING   | 2        | The task is running.|
2434| CANCELED  | 3        | The task is canceled.|
2435
2436
2437## TaskInfo<sup>10+</sup>
2438
2439Describes the internal information about a task.
2440
2441**System capability**: SystemCapability.Utils.Lang
2442
2443### Properties
2444
2445**System capability**: SystemCapability.Utils.Lang
2446
2447| Name    | Type               | Readable| Writable| Description                                                          |
2448| -------- | ------------------ | ---- | ---- | ------------------------------------------------------------- |
2449| name<sup>12+</sup> | string             | Yes  | No  | Task name.<br> **Atomic service API**: This API can be used in atomic services since API version 12.                                                   |
2450| taskId   | number             | Yes  | No  | Task ID.<br> **Atomic service API**: This API can be used in atomic services since API version 11.                                                    |
2451| state    | [State](#state10)  | Yes  | No  | Task state.<br> **Atomic service API**: This API can be used in atomic services since API version 11.                                                   |
2452| 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.<br> **Atomic service API**: This API can be used in atomic services since API version 11. |
2453
2454## ThreadInfo<sup>10+</sup>
2455
2456Describes the internal information about a worker thread.
2457
2458**System capability**: SystemCapability.Utils.Lang
2459
2460### Properties
2461
2462**System capability**: SystemCapability.Utils.Lang
2463
2464**Atomic service API**: This API can be used in atomic services since API version 11.
2465
2466| Name    | Type                   | Readable| Writable| Description                                                     |
2467| -------- | ---------------------- | ---- | ---- | -------------------------------------------------------- |
2468| tid      | number                 | Yes  | No  | ID of the worker thread. If the return value is empty, no task is running.             |
2469| taskIds  | number[]               | Yes  | No  | IDs of tasks running on the calling thread. If the return value is empty, no task is running.  |
2470| priority | [Priority](#priority)  | Yes  | No  | Priority of the calling thread. If the return value is empty, no task is running.             |
2471
2472## TaskPoolInfo<sup>10+</sup>
2473
2474Describes the internal information about a task pool.
2475
2476**System capability**: SystemCapability.Utils.Lang
2477
2478### Properties
2479
2480**System capability**: SystemCapability.Utils.Lang
2481
2482**Atomic service API**: This API can be used in atomic services since API version 11.
2483
2484| Name         | Type                             | Readable| Writable| Description                 |
2485| ------------- | -------------------------------- | ---- | ---- | -------------------- |
2486| threadInfos   | [ThreadInfo[]](#threadinfo10)    | Yes  | No  | Internal information about the worker threads.  |
2487| taskInfos     | [TaskInfo[]](#taskinfo10)        | Yes  | No  | Internal information about the tasks.      |
2488
2489
2490## Additional Information
2491
2492### Sequenceable Data Types
2493The following sequenceable data types are supported: [common object](../../arkts-utils/normal-object.md), [ArrayBuffer object](../../arkts-utils/arraybuffer-object.md), [SharedArrayBuffer object](../../arkts-utils/shared-arraybuffer-object.md), [Transferable object (NativeBinding object)](../../arkts-utils/transferabled-object.md), and [Sendable object](../../arkts-utils/arkts-sendable.md).
2494
2495### Using the Task Pool in Simple Mode
2496
2497**Example 1**
2498
2499```ts
2500// Common functions are supported, and variables passed in by input parameters are also supported.
2501@Concurrent
2502function printArgs(args: string): string {
2503  console.info("func: " + args);
2504  return args;
2505}
2506
2507async function taskpoolExecute(): Promise<void> {
2508  // taskpool.execute(task)
2509  let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
2510  console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
2511  // taskpool.execute(function)
2512  console.info("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
2513}
2514
2515taskpoolExecute();
2516```
2517
2518**Example 2**
2519
2520```ts
2521// b.ets
2522export let c: string = "hello";
2523```
2524<!--code_no_check-->
2525```ts
2526// Reference an imported variable.
2527// a.ets (in the same directory as b.ets)
2528import { c } from "./b";
2529
2530@Concurrent
2531function printArgs(a: string): string {
2532  console.info(a);
2533  console.info(c);
2534  return a;
2535}
2536
2537async function taskpoolExecute(): Promise<void> {
2538  // taskpool.execute(task)
2539  let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute");
2540  console.info("taskpool.execute(task) result: " + await taskpool.execute(task));
2541
2542  // taskpool.execute(function)
2543  console.info("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func"));
2544}
2545
2546taskpoolExecute();
2547```
2548
2549**Example 3**
2550
2551```ts
2552// The async functions are supported.
2553@Concurrent
2554async function delayExecute(): Promise<Object> {
2555  let ret = await Promise.all<Object>([
2556    new Promise<Object>(resolve => setTimeout(resolve, 1000, "resolved"))
2557  ]);
2558  return ret;
2559}
2560
2561async function taskpoolExecute(): Promise<void> {
2562  taskpool.execute(delayExecute).then((result: Object) => {
2563    console.info("taskPoolTest task result: " + result);
2564  }).catch((err: string) => {
2565    console.error("taskpool test occur error: " + err);
2566  });
2567}
2568
2569taskpoolExecute();
2570```
2571
2572**Example 4**
2573
2574```ts
2575// c.ets
2576import { taskpool } from '@kit.ArkTS';
2577
2578@Concurrent
2579function strSort(inPutArr: Array<string>): Array<string> {
2580  let newArr = inPutArr.sort();
2581  return newArr;
2582}
2583
2584export async function func1(): Promise<void> {
2585  console.info("taskpoolTest start");
2586  let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
2587  let task: taskpool.Task = new taskpool.Task(strSort, strArray);
2588  console.info("func1 result:" + await taskpool.execute(task));
2589}
2590
2591export async function func2(): Promise<void> {
2592  console.info("taskpoolTest2 start");
2593  let strArray: Array<string> = ['c test string', 'b test string', 'a test string'];
2594  taskpool.execute(strSort, strArray).then((result: Object) => {
2595    console.info("func2 result: " + result);
2596  }).catch((err: string) => {
2597    console.error("taskpool test occur error: " + err);
2598  });
2599}
2600```
2601<!--code_no_check-->
2602```ts
2603// index.ets
2604import { func1, func2 } from "./c";
2605
2606func1();
2607func2();
2608```
2609
2610**Example 5**
2611
2612```ts
2613// Success in canceling a task
2614@Concurrent
2615function inspectStatus(arg: number): number {
2616  // Check whether the task has been canceled and respond accordingly.
2617  if (taskpool.Task.isCanceled()) {
2618    console.info("task has been canceled before 2s sleep.");
2619    return arg + 2;
2620  }
2621  // 2s sleep
2622  let t: number = Date.now();
2623  while (Date.now() - t < 2000) {
2624    continue;
2625  }
2626  // Check again whether the task has been canceled and respond accordingly.
2627  if (taskpool.Task.isCanceled()) {
2628    console.info("task has been canceled after 2s sleep.");
2629    return arg + 3;
2630  }
2631  return arg + 1;
2632}
2633
2634async function taskpoolCancel(): Promise<void> {
2635  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
2636  taskpool.execute(task).then((res: Object) => {
2637    console.info("taskpool test result: " + res);
2638  }).catch((err: string) => {
2639    console.error("taskpool test occur error: " + err);
2640  });
2641  // Cancel the task 1s later.
2642  setTimeout(() => {
2643    try {
2644      taskpool.cancel(task);
2645    } catch (e) {
2646      console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
2647    }
2648  }, 1000);
2649}
2650
2651taskpoolCancel();
2652```
2653
2654**Example 6**
2655
2656```ts
2657// Failure to cancel a task that has been executed
2658@Concurrent
2659function inspectStatus(arg: number): number {
2660  // Check whether the task has been canceled and respond accordingly.
2661  if (taskpool.Task.isCanceled()) {
2662    return arg + 2;
2663  }
2664  // Wait for 2s.
2665  let t: number = Date.now();
2666  while (Date.now() - t < 500) {
2667    continue;
2668  }
2669  // Check again whether the task has been canceled and respond accordingly.
2670  if (taskpool.Task.isCanceled()) {
2671    return arg + 3;
2672  }
2673  return arg + 1;
2674}
2675
2676async function taskpoolCancel(): Promise<void> {
2677  let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number
2678  taskpool.execute(task).then((res: Object) => {
2679    console.info("taskpool test result: " + res);
2680  }).catch((err: string) => {
2681    console.error("taskpool test occur error: " + err);
2682  });
2683
2684  setTimeout(() => {
2685    try {
2686      taskpool.cancel(task); // The task has been executed and fails to be canceled.
2687    } catch (e) {
2688      console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
2689    }
2690  }, 3000); // Wait for 3s to ensure that the task has been executed.
2691}
2692
2693taskpoolCancel();
2694```
2695
2696**Example 7**
2697
2698```ts
2699// Success of canceling a task group to be executed
2700@Concurrent
2701function printArgs(args: number): number {
2702  let t: number = Date.now();
2703  while (Date.now() - t < 1000) {
2704    continue;
2705  }
2706  console.info("printArgs: " + args);
2707  return args;
2708}
2709
2710async function taskpoolGroupCancelTest(): Promise<void> {
2711  let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup();
2712  taskGroup1.addTask(printArgs, 10); // 10: test number
2713  taskGroup1.addTask(printArgs, 20); // 20: test number
2714  taskGroup1.addTask(printArgs, 30); // 30: test number
2715  let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup();
2716  let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number
2717  let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number
2718  let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number
2719  taskGroup2.addTask(task1);
2720  taskGroup2.addTask(task2);
2721  taskGroup2.addTask(task3);
2722  taskpool.execute(taskGroup1).then((res: Array<Object>) => {
2723    console.info("taskpool execute res is:" + res);
2724  }).catch((e: string) => {
2725    console.error("taskpool execute error is:" + e);
2726  });
2727  taskpool.execute(taskGroup2).then((res: Array<Object>) => {
2728    console.info("taskpool execute res is:" + res);
2729  }).catch((e: string) => {
2730    console.error("taskpool execute error is:" + e);
2731  });
2732
2733  try {
2734    taskpool.cancel(taskGroup2);
2735  } catch (e) {
2736    console.error(`taskpool: cancel error code: ${e.code}, info: ${e.message}`);
2737  }
2738}
2739
2740taskpoolGroupCancelTest()
2741```
2742
2743**Example 8**
2744
2745```ts
2746// Create and execute 100 tasks with different priorities, and view their information.
2747@Concurrent
2748function delay(): void {
2749  let start: number = new Date().getTime();
2750  while (new Date().getTime() - start < 500) {
2751    continue;
2752  }
2753}
2754
2755let highCount: number = 0;
2756let mediumCount: number = 0;
2757let lowCount: number = 0;
2758let allCount: number = 100;
2759for (let i = 0; i < allCount; i++) {
2760  let task1: taskpool.Task = new taskpool.Task(delay);
2761  let task2: taskpool.Task = new taskpool.Task(delay);
2762  let task3: taskpool.Task = new taskpool.Task(delay);
2763  taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
2764    lowCount++;
2765  }).catch((e: string) => {
2766    console.error("low task error: " + e);
2767  })
2768  taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
2769    mediumCount++;
2770  }).catch((e: string) => {
2771    console.error("medium task error: " + e);
2772  })
2773  taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
2774    highCount++;
2775  }).catch((e: string) => {
2776    console.error("high task error: " + e);
2777  })
2778}
2779let start: number = new Date().getTime();
2780while (new Date().getTime() - start < 1000) {
2781  continue;
2782}
2783let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo();
2784let tid: number = 0;
2785let taskIds: Array<number> = [];
2786let priority: number = 0;
2787let taskId: number = 0;
2788let state: number = 0;
2789let duration: number = 0;
2790let name: string = "";
2791let threadIS = Array.from(taskpoolInfo.threadInfos)
2792for (let threadInfo of threadIS) {
2793  tid = threadInfo.tid;
2794  if (threadInfo.taskIds != undefined && threadInfo.priority != undefined) {
2795    taskIds.length = threadInfo.taskIds.length;
2796    priority = threadInfo.priority;
2797  }
2798  console.info("taskpool---tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority);
2799}
2800let taskIS = Array.from(taskpoolInfo.taskInfos)
2801for (let taskInfo of taskIS) {
2802  taskId = taskInfo.taskId;
2803  state = taskInfo.state;
2804  if (taskInfo.duration != undefined) {
2805    duration = taskInfo.duration;
2806    name = taskInfo.name;
2807  }
2808  console.info("taskpool---taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration + ", name is:" + name);
2809}
2810```
2811