#鸿蒙通关秘籍#鸿蒙API 13中如何让Task在执行过程中通知宿主线程?

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
GUI风轨迹

通过Task的sendData方法可以在任务执行过程中,实时通知宿主线程。

首先在宿主线程中定义接收消息的方法:

bash // TaskSendDataUsage.ets function notice(data: number): void { console.info("子线程任务已执行完,共加载图片: ", data); }

在任务中使用sendData发送消息:

bash // TaskSendDataUsage.ets import { taskpool } from '@kit.ArkTS'; import { IconItemSource } from './IconItemSource';

@Concurrent export function loadPictureSendData(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}));

taskpool.Task.sendData(iconItemSourceList.length);

} return iconItemSourceList; }

在主线程中注册接收消息:

bash // TaskSendDataUsage.ets @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(loadPictureSendData, 30); lodePictureTask.onReceiveData(notice); taskpool.execute(lodePictureTask).then((res: object) => { iconItemSourceList = res as IconItemSource[]; }) }) } .width('100%') } .height('100%') } }

分享
微博
QQ
微信
回复
3天前
相关问题
Worker的宿主线程必须是主线程吗?
407浏览 • 1回复 待解决