1# 使用TaskPool执行独立的耗时任务 2 3对于一个独立运行的耗时任务,只需要在任务执行完毕后将结果返回给宿主线程,没有上下文依赖,可以通过以下方式实现。 4 5下面以图片加载为例进行说明。 6 71. 实现子线程需要执行的任务。 8 9 ```ts 10 // IconItemSource.ets 11 export class IconItemSource { 12 image: string | Resource = ''; 13 text: string | Resource = ''; 14 15 constructor(image: string | Resource = '', text: string | Resource = '') { 16 this.image = image; 17 this.text = text; 18 } 19 } 20 ``` 21 22 ```ts 23 // IndependentTask.ets 24 import { IconItemSource } from './IconItemSource'; 25 26 // 在Task中执行的方法,需要添加@Concurrent注解,否则无法正常调用。 27 @Concurrent 28 export function loadPicture(count: number): IconItemSource[] { 29 let iconItemSourceList: IconItemSource[] = []; 30 // 遍历添加6*count个IconItem的数据 31 for (let index = 0; index < count; index++) { 32 const numStart: number = index * 6; 33 // 此处循环使用6张图片资源 34 iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 1}`)); 35 iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 2}`)); 36 iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 3}`)); 37 iconItemSourceList.push(new IconItemSource('$media:startIcon', `item${numStart + 4}`)); 38 iconItemSourceList.push(new IconItemSource('$media:background', `item${numStart + 5}`)); 39 iconItemSourceList.push(new IconItemSource('$media:foreground', `item${numStart + 6}`)); 40 } 41 return iconItemSourceList; 42 } 43 ``` 44 452. 通过TaskPool中的execute方法执行上述任务,即加载图片。 46 47 ```ts 48 // Index.ets 49 import { taskpool } from '@kit.ArkTS'; 50 import { IconItemSource } from './IconItemSource'; 51 import { loadPicture } from './IndependentTask'; 52 53 @Entry 54 @Component 55 struct Index { 56 @State message: string = 'Hello World'; 57 58 build() { 59 Row() { 60 Column() { 61 Text(this.message) 62 .fontSize(50) 63 .fontWeight(FontWeight.Bold) 64 .onClick(() => { 65 let iconItemSourceList: IconItemSource[] = []; 66 // 创建Task 67 let lodePictureTask: taskpool.Task = new taskpool.Task(loadPicture, 30); 68 // 执行Task,并返回结果 69 taskpool.execute(lodePictureTask).then((res: object) => { 70 // loadPicture方法的执行结果 71 iconItemSourceList = res as IconItemSource[]; 72 }) 73 }) 74 } 75 .width('100%') 76 } 77 .height('100%') 78 } 79 } 80 ``` 81