1# I/O密集型任务开发指导 (TaskPool)
2
3
4使用异步并发可以解决单次I/O任务阻塞的问题,但是如果遇到I/O密集型任务,同样会阻塞线程中其它任务的执行,这时需要使用多线程并发能力来进行解决。
5
6
7I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/O操作的速度和效率。这种任务通常需要频繁地进行磁盘读写、网络通信等操作。此处以频繁读写系统文件来模拟I/O密集型并发任务的处理。
8
9
101. 定义并发函数,内部密集调用I/O能力。
11    ```ts
12    // write.ets
13    import { fileIo } from '@kit.CoreFileKit'
14
15    // 定义并发函数,内部密集调用I/O能力
16    // 写入文件的实现
17    export async function write(data: string, filePath: string): Promise<void> {
18      let file: fileIo.File = await fileIo.open(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
19      await fileIo.write(file.fd, data);
20      fileIo.close(file);
21    }
22    ```
23
24	```ts
25    // Index.ets
26    import { write } from './write'
27    import { BusinessError } from '@kit.BasicServicesKit';
28    import { taskpool } from '@kit.ArkTS';
29    import { common } from '@kit.AbilityKit';
30
31    @Concurrent
32    async function concurrentTest(context: common.UIAbilityContext): Promise<boolean> {
33      let filePath1: string = context.filesDir + "/path1.txt"; // 应用文件路径
34      let filePath2: string = context.filesDir + "/path2.txt";
35      // 循环写文件操作
36      let fileList: Array<string> = [];
37      fileList.push(filePath1);
38      fileList.push(filePath2)
39      for (let i: number = 0; i < fileList.length; i++) {
40        write('Hello World!', fileList[i]).then(() => {
41          console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`);
42        }).catch((err: BusinessError) => {
43          console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`)
44          return false;
45        })
46      }
47      return true;
48    }
49	```
50
512. 使用TaskPool执行包含密集I/O的并发函数:通过调用[execute()](../reference/apis-arkts/js-apis-taskpool.md#taskpoolexecute)方法执行任务,并在回调中进行调度结果处理。示例中获取filePath1和filePath2的方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径),在TaskPool中使用context需先在并发函数外部准备好,通过入参传递给并发函数才可使用。
52
53    ```ts
54    // Index.ets
55    @Entry
56    @Component
57    struct Index {
58      @State message: string = 'Hello World';
59      build() {
60        Row() {
61          Column() {
62            Text(this.message)
63              .fontSize(50)
64              .fontWeight(FontWeight.Bold)
65              .onClick(() => {
66                let context = getContext() as common.UIAbilityContext;
67
68                // 使用TaskPool执行包含密集I/O的并发函数
69                // 数组较大时,I/O密集型任务任务分发也会抢占UI主线程,需要使用多线程能力
70                taskpool.execute(concurrentTest, context).then(() => {
71                  // 调度结果处理
72                  console.info("taskpool: execute success")
73                })
74              })
75          }
76          .width('100%')
77        }
78        .height('100%')
79      }
80    }
81    ```
82