#鸿蒙通关秘籍#在鸿蒙API 13中如何使用TaskPool同时执行多个耗时任务?

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
雪域狼GUI

使用TaskPool的TaskGroup来同时处理多个任务。首先实现需要执行的任务:

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; }

将任务放入TaskGroup并执行:

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

let iconItemSourceList: IconItemSource[][];

let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup.addTask(new taskpool.Task(loadPicture, 30)); taskGroup.addTask(new taskpool.Task(loadPicture, 20)); taskGroup.addTask(new taskpool.Task(loadPicture, 10)); taskpool.execute(taskGroup).then((ret: object) => { let tmpLength = (ret as IconItemSource[][]).length; for (let i = 0; i < tmpLength; i++) { for (let j = 0; j < ret[i].length; j++) { iconItemSourceList.push(ret[i][j]); } } });

分享
微博
QQ
微信
回复
2天前
相关问题
如何申请多个时任务
1963浏览 • 1回复 待解决
如何利用taskpool执行任务
2032浏览 • 1回复 待解决