鸿蒙next开发:I/O密集型任务开发指南 (TaskPool)

往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)


I/O密集型任务开发指南 (TaskPool)

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

I/O密集型任务的性能关键在于I/O操作的速度和效率,而非CPU的处理能力。这类任务需要频繁进行磁盘读写和网络通信。此处通过频繁读写系统文件来模拟I/O密集型并发任务的处理。

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

    // write.ets
    import { fileIo } from '@kit.CoreFileKit'
    
    // 定义并发函数,内部密集调用I/O能力
    // 写入文件的实现
    export async function write(data: string, filePath: string): Promise<void> {
      let file: fileIo.File = await fileIo.open(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
      await fileIo.write(file.fd, data);
      fileIo.close(file);
    }
    // Index.ets
    import { write } from './write'
    import { BusinessError } from '@kit.BasicServicesKit';
    import { taskpool } from '@kit.ArkTS';
    import { common } from '@kit.AbilityKit';
    
    @Concurrent
    async function concurrentTest(context: common.UIAbilityContext): Promise<boolean> {
      let filePath1: string = context.filesDir + "/path1.txt"; // 应用文件路径
      let filePath2: string = context.filesDir + "/path2.txt";
      // 循环写文件操作
      let fileList: Array<string> = [];
      fileList.push(filePath1);
      fileList.push(filePath2)
      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;
    }
  2. 使用TaskPool执行包含密集I/O的并发函数,通过调用execute()方法执行任务,并在回调中处理调度结果。示例中获取filePath1和filePath2的方式请参见获取应用文件路径。在TaskPool中使用context时,需先在并发函数外部准备好,并通过参数传递给并发函数。

    // Index.ets
    @Entry
    @Component
    struct Index {
      @State message: string = 'Hello World';
      build() {
        Row() {
          Column() {
            Text(this.message)
              .fontSize(50)
              .fontWeight(FontWeight.Bold)
              .onClick(() => {
                let context = getContext() as common.UIAbilityContext;
    
                // 使用TaskPool执行包含密集I/O的并发函数
                // 数组较大时,I/O密集型任务分发也会抢占UI主线程,需要使用多线程能力
                taskpool.execute(concurrentTest, context).then(() => {
                  // 调度结果处理
                  console.info("taskpool: execute success")
                })
              })
          }
          .width('100%')
        }
        .height('100%')
      }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值