#鸿蒙通关秘籍#如何在鸿蒙API 13中实现独立执行的耗时任务?

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
疏影横斜水清浅COO

要实现独立运行的耗时任务,可以使用TaskPool。首先,定义要在子线程中执行的任务:

bash // IndependentTask.ets import { IconItemSource } from './IconItemSource';

@Concurrent export function loadPicture(count: number): IconItemSource[] { let iconItemSourceList: IconItemSource[] = []; for (let index = 0; index < count; index++) { const numStart: number = index * 6; iconItemSourceList.push(new IconItemSource('$media:startIcon', item${numStart + 1})); iconItemSourceList.push(new IconItemSource('$media:background', item${numStart + 2})); iconItemSourceList.push(new IconItemSource('$media:foreground', item${numStart + 3})); iconItemSourceList.push(new IconItemSource('$media:startIcon', item${numStart + 4})); iconItemSourceList.push(new IconItemSource('$media:background', item${numStart + 5})); iconItemSourceList.push(new IconItemSource('$media:foreground', item${numStart + 6})); } return iconItemSourceList; }

然后,在主线程中执行这个任务:

bash // Index.ets import { taskpool } from '@kit.ArkTS'; import { IconItemSource } from './IconItemSource'; import { loadPicture } from './IndependentTask';

@Entry @Component struct Index { @State message: string = 'Hello World';

build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { let iconItemSourceList: IconItemSource[] = []; let lodePictureTask: taskpool.Task = new taskpool.Task(loadPicture, 30); taskpool.execute(lodePictureTask).then((res: object) => { iconItemSourceList = res as IconItemSource[]; }) }) } .width('100%') } .height('100%') } }

分享
微博
QQ
微信
回复
2天前
相关问题