#鸿蒙通关秘籍#在鸿蒙API 13环境中Worker如何实现和宿主线程的即时消息通信?

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
墨sY空QC

使用Worker实现和宿主线程的双向通信,Worker可以接收和发送消息。

在Worker中实现消息处理逻辑:

bash // Worker.ets import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';

const workerPort: ThreadWorkerGlobalScope = worker.workerPort; workerPort.onmessage = (e: MessageEvents): void => { if (e.data === 'hello world') { workerPort.postMessage('success'); } }

在宿主线程中创建Worker对象并处理通信:

bash // Index.ets import { worker } from '@kit.ArkTS'; import { BusinessError } from '@kit.BasicServicesKit';

function promiseCase() { let p: Promise<void> = new Promise<void>((resolve: Function, reject: Function) => { setTimeout(() => { resolve(1); }, 100) }).then(undefined, (error: BusinessError) => { }) return p; }

async function postMessageTest() { let ss = new worker.ThreadWorker("entry/ets/workers/Worker.ets"); let res = undefined; let flag = false; let isTerminate = false; ss.onexit = () => { isTerminate = true; } ss.onmessage = (e) => { res = e.data; flag = true; console.info("worker:: res is " + res); } ss.postMessage("hello world"); while (!flag) { await promiseCase(); }

ss.terminate(); while (!isTerminate) { await promiseCase(); } }

@Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { postMessageTest(); }) } .width('100%') } .height('100%') } }

分享
微博
QQ
微信
回复
2天前
相关问题
Worker宿主线程必须是主线程吗?
404浏览 • 1回复 待解决
TaskPool子线程主线程如何通信
2304浏览 • 1回复 待解决
hi3861环境编译出现编码问题
11773浏览 • 1回复 待解决