#鸿蒙学习大百科#如何用TaskPool实现一个I/O密集型任务?

如何用TaskPool实现一个I/O密集型任务?

HarmonyOS
2024-10-16 08:40:50
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
耗子煨汁r
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);
}

分享
微博
QQ
微信
回复
2024-10-16 15:19:40
相关问题