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 {
    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.鸿蒙南向开发方向

相关推荐
资料库019 分钟前
华为M-LAG(跨设备链路聚合组)
华为
网络豆11 小时前
开源鸿蒙平台 CMP 三方库「navigation-compose-extended」适配全流程
华为·开源·harmonyos
2601_9494800613 小时前
开源鸿蒙平台 CMP 三方库「multiplatform-markdown-renderer」适配全流程
华为·开源·harmonyos
威哥爱编程15 小时前
HarmonyOS 7 Agent 开发实战 10:降级兜底与重试
agent·harmonyos
威哥爱编程15 小时前
HarmonyOS 7 Agent 开发实战 11:并发多会话隔离
agent·harmonyos
威哥爱编程16 小时前
HarmonyOS 7 Agent 开发实战 12:人机协同与人工接管
agent·harmonyos
鸿蒙开发16 小时前
鸿蒙动态表单实战:用 @hmkit/validator 处理条件必填与错误联动
harmonyos
行者-全栈开发16 小时前
【共创稿事节】HarmonyOS 三方库工程化集成:从 ohpm 引入到三方库鸿蒙化的完整闭环
harmonyos·鸿蒙·har·三方库·ohpm·框架适配
网络豆17 小时前
开源鸿蒙平台 CMP 三方库「tanstack-table-kmp」适配全流程
华为·开源·harmonyos
贾伟康18 小时前
【共创稿事节】食材百科页的懒加载改造:LazyForEach、IDataSource 与缓存窗口的三次迭代
性能优化·harmonyos·arkts·lazyforeach·列表加载