中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
如何使用Worker完成一个计算任务?
微信扫码分享
import { MessageEvents, worker } from '@kit.ArkTS'; @Entry @Component struct Page_Context { @State result: number = 0 build() { Column() { Text("result:" + this.result) Button("Click Me").onClick(() => { let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); w.onmessage = (event: MessageEvents) => { this.result = event.data.result w.terminate() } w.onerror = () => { } w.postMessage({ "a": 1, "b": 2, "type": "sum" }) }) }.width("100%") .height("100%") } } MyWorker.ets workerPort.onmessage = (e: MessageEvents) => { let a = e.data.a as number let b = e.data.b as number let type = e.data.type as string if ("sum" === type) { let sum = a + b; workerPort.postMessage({ "result": (sum) }) } }