如何使用TaskPool在子线程调用对象成员函数

在使用taskpool的时候,无法在子线程中调用对象的成员函数,具体该怎么调用?

HarmonyOS
2024-09-18 12:04:14
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zbw_apple

参考答复:

可以通过将对象sendable化来使用对象中的方法。

参考链接:

sendable

参考代码:

// Index.ets代码 
import taskpool from '@ohos.taskpool'; 
import { SendClass } from './SendClass'; 
 
let sendClass2 = new SendClass(); 
 
// 步骤1: 定义并发函数,内部调用同步方法 
@Concurrent 
function func(arr: Array<SendClass>): number { 
  let test = arr[0]; 
  let sum = test.GetValue() + 1; 
  return sum; 
} 
 
// 步骤2: 创建任务并执行 
function syncGet(): void { 
  let array1 = new Array<SendClass>(); 
  array1.push(sendClass2); 
  let task: taskpool.Task = new taskpool.Task(func, array1); 
  task.setCloneList(array1); 
  taskpool.execute(task).then((result: object) => { 
    console.log("testTag result:" + result); 
  }); 
} 
 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World'; 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.message) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
          .onClick(() => { 
            // 步骤3: 执行并发操作 
            syncGet(); 
          }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
@Sendable 
export class SendClass { 
  value: number = 888; 
 
  GetValue(): number { 
    return this.value; 
  } 
 
  Print(): void { 
    console.log("value:" + this.value); 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
分享
微博
QQ
微信
回复
2024-09-18 17:06:38
相关问题
TaskPool线程和主线程如何通信
3259浏览 • 1回复 待解决
ArkTS调用C++类中的成员函数
2313浏览 • 1回复 待解决
HarmonyOS TaskPool线程单例问题
1165浏览 • 1回复 待解决
NAPI跨线程调用TS线程函数
2458浏览 • 1回复 待解决
如何使用taskpool实现多线程
2009浏览 • 1回复 待解决
TaskPool是否可以访问静态成员
2423浏览 • 1回复 待解决
HarmonyOS 线程支持设置类对象类型
754浏览 • 1回复 待解决
HarmonyOS huks支持线程调用吗?
664浏览 • 1回复 待解决