• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# I/O密集型任务开发指导 (TaskPool)
2<!--Kit: ArkTS-->
3<!--Subsystem: CommonLibrary-->
4<!--Owner: @lijiamin2025-->
5<!--Designer: @weng-changcheng-->
6<!--Tester: @kirl75; @zsw_zhushiwei-->
7<!--Adviser: @ge-yafang-->
8
9
10使用异步并发可以解决单次I/O任务阻塞的问题。对于I/O密集型任务,若线程中的其他任务仍可能被阻塞,建议采用多线程并发来处理。
11
12
13I/O密集型任务的性能关键在于I/O操作的速度和效率,而非CPU的处理能力。这类任务需要频繁进行磁盘读写和网络通信。此处通过频繁读写系统文件来模拟I/O密集型并发任务的处理。
14
15
161. 定义并发函数,内部密集调用I/O能力。
17    ```ts
18    // write.ets
19    import { fileIo } from '@kit.CoreFileKit';
20
21    // 定义并发函数,内部频繁调用I/O能力
22    // 写入文件的实现
23    export async function write(data: string, filePath: string): Promise<void> {
24      let file: fileIo.File = await fileIo.open(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
25      await fileIo.write(file.fd, data);
26      fileIo.close(file);
27    }
28    ```
29    <!-- @[define_concurrent_function](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/ApplicationMultithreading/entry/src/main/ets/managers/write.ets) -->
30
31	```ts
32    // Index.ets
33    import { write } from './write';
34    import { BusinessError } from '@kit.BasicServicesKit';
35    import { taskpool } from '@kit.ArkTS';
36    import { common } from '@kit.AbilityKit';
37
38    @Concurrent
39    async function concurrentTest(context: common.UIAbilityContext): Promise<void> {
40      // 应用文件路径
41      let filePath1: string = context.filesDir + "/path1.txt";
42      let filePath2: string = context.filesDir + "/path2.txt";
43      // 循环写文件操作
44      let fileList: Array<string> = [];
45      fileList.push(filePath1);
46      fileList.push(filePath2);
47      for (let i: number = 0; i < fileList.length; i++) {
48        write('Hello World!', fileList[i]).then(() => {
49          console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`);
50        }).catch((err: BusinessError) => {
51          console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`);
52        })
53      }
54      return;
55    }
56	```
57  <!-- @[define_concurrent_function](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/ApplicationMultithreading/entry/src/main/ets/managers/IoIntensiveTaskDevelopment.ets) -->
58
592. 使用TaskPool执行包含密集I/O的并发函数,通过调用[execute()](../reference/apis-arkts/js-apis-taskpool.md#taskpoolexecute)方法执行任务,并在回调中处理调度结果。示例中获取filePath1和filePath2的方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。在TaskPool中使用context时,需先在并发函数外部准备好,并通过参数传递给并发函数。
60
61    ```ts
62    // Index.ets
63    @Entry
64    @Component
65    struct Index {
66      @State message: string = 'Hello World';
67      build() {
68        Row() {
69          Column() {
70            Text(this.message)
71              .fontSize(50)
72              .fontWeight(FontWeight.Bold)
73              .onClick(() => {
74                let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
75
76                // 使用TaskPool执行包含密集I/O的并发函数
77                // 数组较大时,I/O密集型任务分发也会抢占UI主线程,需要使用多线程能力
78                taskpool.execute(concurrentTest, context).then(() => {
79                  // 调度结果处理
80                  console.info("taskpool: execute success");
81                })
82              })
83          }
84          .width('100%')
85        }
86        .height('100%')
87      }
88    }
89    ```
90    <!-- @[taskpool_execute_concurrent_function](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/ApplicationMultithreading/entry/src/main/ets/managers/IoIntensiveTaskDevelopment.ets) -->
91