HarmonyOS 应用开发之I/O密集型任务开发指导 (TaskPool)

使用异步并发可以解决单次I/O任务阻塞的问题,但是如果遇到I/O密集型任务,同样会阻塞线程中其它任务的执行,这时需要使用多线程并发能力来进行解决。

I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/O操作的速度和效率。这种任务通常需要频繁地进行磁盘读写、网络通信等操作。此处以频繁读写系统文件来模拟I/O密集型并发任务的处理。

  1. 定义并发函数,内部密集调用I/O能力。

    // a.ts
    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);
    await fs.write(file.fd, data);
    fs.close(file);
    }


复制代码
import { write } from './a'
import { BusinessError } from '@ohos.base';

@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;
}
  1. 使用TaskPool执行包含密集I/O的并发函数:通过调用 execute() 方法执行任务,并在回调中进行调度结果处理。

    import taskpool from '@ohos.taskpool';

    let filePath1: string = "path1"; // 应用文件路径
    let filePath2: string = "path2";

    // 使用TaskPool执行包含密集I/O的并发函数
    // 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力
    taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => {
    // 调度结果处理
    })

为了能让大家更好的学习鸿蒙(HarmonyOS NEXT)开发技术,这边特意整理了《鸿蒙开发学习手册》(共计890页),希望对大家有所帮助:https://qr21.cn/FV7h05

《鸿蒙开发学习手册》:

如何快速入门:https://qr21.cn/FV7h05

  1. 基本概念
  2. 构建第一个ArkTS应用
  3. ......

开发基础知识:https://qr21.cn/FV7h05

  1. 应用基础知识
  2. 配置文件
  3. 应用数据管理
  4. 应用安全管理
  5. 应用隐私保护
  6. 三方应用调用管控机制
  7. 资源分类与访问
  8. 学习ArkTS语言
  9. ......

基于ArkTS 开发:https://qr21.cn/FV7h05

  1. Ability开发
  2. UI开发
  3. 公共事件与通知
  4. 窗口管理
  5. 媒体
  6. 安全
  7. 网络与链接
  8. 电话服务
  9. 数据管理
  10. 后台任务(Background Task)管理
  11. 设备管理
  12. 设备使用信息统计
  13. DFX
  14. 国际化开发
  15. 折叠屏系列
  16. ......

鸿蒙开发面试真题(含参考答案):https://qr18.cn/F781PH

鸿蒙开发面试大盘集篇(共计319页):https://qr18.cn/F781PH

1.项目开发必备面试题

2.性能优化方向

3.架构方向

4.鸿蒙开发系统底层方向

5.鸿蒙音视频开发方向

6.鸿蒙车载开发方向

7.鸿蒙南向开发方向

相关推荐
安卓开发者34 分钟前
鸿蒙NEXT主题设置指南:应用级与页面级主题定制详解
华为·harmonyos
深盾科技6 小时前
鸿蒙ABC开发中的名称混淆与反射处理策略:安全与效率的平衡
安全·华为·harmonyos
fakerth7 小时前
【OpenHarmony文件管理子系统】文件访问接口解析
操作系统·openharmony
2501_919749038 小时前
鸿蒙:获取UIContext实例的方法
华为·harmonyos
王佳斌10 小时前
tp报错解决
harmonyos
coooliang10 小时前
【鸿蒙 NEXT】V1迁移V2状态管理
java·前端·harmonyos
江拥羡橙12 小时前
【目录-单选】鸿蒙HarmonyOS开发者基础
前端·ui·华为·typescript·harmonyos
爱笑的眼睛1112 小时前
HarmonyOS应用开发:深入ArkUI声明式开发范式与最佳实践
华为·harmonyos
云水木石13 小时前
开源鸿蒙+龙芯CPU,能擦出怎样的火花?
华为·开源·harmonyos
特立独行的猫a14 小时前
开源OpenHarmony润开鸿HH-SCDAYU800A开发板开箱体验
开源·harmonyos·openharmony·hh-scdayu800a