#鸿蒙学习大百科#如何使用Worker完成一个计算任务?

如何使用Worker完成一个计算任务?

HarmonyOS
2024-10-16 08:28:32
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
莫名瞄一眼
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) })
  }

}
分享
微博
QQ
微信
回复
2024-10-16 16:42:28
相关问题