• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 使用TaskPool执行多个耗时任务
2<!--Kit: ArkTS-->
3<!--Subsystem: CommonLibrary-->
4<!--Owner: @lijiamin2025-->
5<!--Designer: @weng-changcheng-->
6<!--Tester: @kirl75; @zsw_zhushiwei-->
7<!--Adviser: @ge-yafang-->
8
9多个任务同时执行时,由于任务复杂度不同,执行时间和返回数据的时间也会不同。如果宿主线程需要所有任务执行完毕的数据,可以通过[TaskGroup](../reference/apis-arkts/js-apis-taskpool.md#taskgroup10)的方式实现。
10
11除了以上情况,如果需要处理的数据量较大,例如一个列表中有10000条数据,将这些数据放在一个Task中处理会非常耗时。那么就可以将原始数据拆分成多个子列表,为每个子列表分配一个独立的Task执行,等待全部Task执行完成后合并结果形成完整的数据,这样可以节省处理时间,提升用户体验。
12
13下面以多个任务进行图片加载为例进行说明。
14
151. 实现子线程中需要执行的任务。
16
17   ```ts
18   // IconItemSource.ets
19   export class IconItemSource {
20     image: string | Resource = '';
21     text: string | Resource = '';
22
23     constructor(image: string | Resource = '', text: string | Resource = '') {
24       this.image = image;
25       this.text = text;
26     }
27   }
28   ```
29   <!-- @[implement_child_thread_task](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationScenario/entry/src/main/ets/managers/IconItemSource.ets) -->
30
31   ```ts
32   // IndependentTask.ets
33   import { IconItemSource } from './IconItemSource';
34
35   // 在TaskPool线程中执行的方法,需要添加@Concurrent注解,否则无法正常调用
36   @Concurrent
37   export function loadPicture(count: number): IconItemSource[] {
38     let iconItemSourceList: IconItemSource[] = [];
39     // 遍历添加6*count个IconItem的数据
40     for (let index = 0; index < count; index++) {
41       const numStart: number = index * 6;
42       // 此处循环使用6张预定义的图片资源(例如:startIcon、background、foreground等)
43       iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 1}`));
44       iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 2}`));
45       iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 3}`));
46       iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 4}`));
47       iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 5}`));
48       iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 6}`));
49
50     }
51     return iconItemSourceList;
52   }
53   ```
54   <!-- @[implement_child_thread_task](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationScenario/entry/src/main/ets/managers/IndependentTask.ets) -->
55
562. 将需要执行的Task放到一个TaskGroup里面,当TaskGroup中的所有Task执行完毕后,会将所有Task的结果都放在一个数组中并返回给宿主线程,而不是每执行完一个Task就返回一次,这样宿主线程就可以在返回的数据里拿到所有Task的执行结果,便于后续使用。
57
58   ```ts
59   // Index.ets
60   import { taskpool } from '@kit.ArkTS';
61   import { IconItemSource } from './IconItemSource';
62   import { loadPicture } from './IndependentTask';
63
64   @Entry
65   @Component
66   struct Index {
67     @State message: string = 'Hello World';
68
69     build() {
70       Row() {
71         Column() {
72           Text(this.message)
73             .fontSize(50)
74             .fontWeight(FontWeight.Bold)
75             .onClick(() => {
76               let iconItemSourceList: IconItemSource[][] = [];
77
78               let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup();
79               taskGroup.addTask(new taskpool.Task(loadPicture, 30));
80               taskGroup.addTask(new taskpool.Task(loadPicture, 20));
81               taskGroup.addTask(new taskpool.Task(loadPicture, 10));
82               taskpool.execute(taskGroup).then((ret: object) => {
83                 let tmpLength = (ret as IconItemSource[][]).length;
84                 for (let i = 0; i < tmpLength; i++) {
85                   for (let j = 0; j < ret[i].length; j++) {
86                     iconItemSourceList.push(ret[i][j]);
87                   }
88                 }
89                 // The length of iconItemSourceList is 360
90                 console.info("The length of iconItemSourceList is " + iconItemSourceList.length);
91               })
92             })
93         }
94         .width('100%')
95       }
96       .height('100%')
97     }
98   }
99   ```
100   <!-- @[execute_task_group](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationScenario/entry/src/main/ets/managers/MultiTask.ets) -->
101