根据官方文档的描述,TaskPool内存是完全独立的,例如有一个后台任务需要执行数据库操作和网络请求功能,如果多次调用TaskPool执行后台任务是否意味着每次都需要初始化数据库和网络请求工具类?有什么方法可以在线程间共享工具类初始化的数据?
可以使用共享模块内导出Sendable对象来实现进程单例,从而达到线程间共享对象。
// 共享模块sharedModule.ets import { ArkTSUtils } from '@kit.ArkTS'; // 声明当前模块为共享模块,只能导出可Sendable数据 'use shared'; // 共享模块,SingletonA全局唯一 @Sendable class SingletonA { private count_: number = 0; lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock(); public async getCount(): Promise<number> { return this.lock_.lockAsync(() => { return this.count_; }); } public async increaseCount() { // 异步锁中自增count await this.lock_.lockAsync(() => { this.count_++; }); } } // 导出单例共享对象 export const singletonA = new SingletonA();
import { taskpool } from '@kit.ArkTS'; import { singletonA } from './SharedModule'; @Concurrent async function increaseCount() { await singletonA.increaseCount(); let count:number = await singletonA.getCount(); console.info(`SharedModule: count is: ${count}`); } @Concurrent async function printCount() { let count:number = await singletonA.getCount(); console.info(`SharedModule: count is: ${count}`); } @Entry @Component struct TaskToolSharedPage { build() { Row() { Column() { Button('MainThread print count') .onClick(async () => { try { await printCount(); } catch (err) { console.error(`MainThread print count.errCode is ${err.code}, message is ${err.message}`); } }) .margin({top:20}); Button('Taskpool print count') .onClick(async () => { try { await taskpool.execute(printCount); } catch (err) { console.error(`Taskpool print count.errCode is ${err.code}, message is ${err.message}`); } }) .margin({top:20}); Button('MainThread increase count') .onClick(async () => { try { await increaseCount(); let count:number = await singletonA.getCount(); console.info(`MainThread SharedModule: count is: ${count}`); } catch (err) { console.error(`MainThread increase count.errCode is ${err.code}, message is ${err.message}`); } }) .margin({top:20}); Button('Taskpool increase count') .onClick(async () => { try { await taskpool.execute(increaseCount); let count:number = await singletonA.getCount(); console.info(`Taskpool SharedModule: count is: ${count}`); } catch (err) { console.error(`Taskpool increase count.errCode is ${err.code}, message is ${err.message}`); } }) .margin({top:20}); } .width('100%'); } .height('100%'); } }
