中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
如何用TaskPool实现一个I/O密集型任务?
微信扫码分享
import { BusinessError } from '@kit.BasicServicesKit'; import { taskpool } from '@kit.ArkTS'; import { common } from '@kit.AbilityKit'; import { write } from '../Utils'; @Concurrent async function concurrentTest(fileList: string[]): Promise<boolean> { // 循环写文件操作 for (let i: number = 0; i < fileList.length; i++) { write('Hello World!', fileList[i]).then(() => { console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); }).catch((err: BusinessError) => { console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) return false; }) } return true; } @Entry @Component struct Index { @State message: string = 'Hello World' private context = getContext(this) as common.UIAbilityContext; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { let applicationContext = this.context.getApplicationContext(); let cacheDir = applicationContext.cacheDir; let filePath1: string = cacheDir + "/aaa"; // 应用文件路径 let filePath2: string = cacheDir + "/bbb"; taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => { //成功 }) }) } .width('100%') } .height('100%') } }
import fs from '@ohos.file.fs'; // 定义并发函数,内部密集调用I/O能力 // 写入文件的实现 export async function write(data: string, filePath: string): Promise<void> { let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE); await fs.write(file.fd, data); fs.close(file); }