• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# I/O Intensive Task Development (TaskPool)
2
3
4I/O intensive tasks are those requiring frequent I/O operations such as disk read/write and network communication. While asynchronous concurrency can address the thread blocking issue for single I/O tasks, it falls short in the case of I/O intensive tasks. This is where multithreaded concurrency comes into play.
5
6
7The performance focus of I/O intensive tasks is not the CPU processing capability, but the speed and efficiency of I/O operations, since these tasks usually require frequent operations such as disk read/write and network communication. The following uses frequent read/write operations on a system file to simulate concurrency processing of I/O intensive tasks.
8
9
101. Define a concurrent function that frequently calls I/O operations.
11    ```ts
12    // write.ets
13    import { fileIo } from '@kit.CoreFileKit'
14
15    // Define a concurrent function that frequently calls I/O operations.
16    // Write data to the file.
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    <!-- @[define_concurrent_function](https://gitee.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/ApplicationMultithreading/entry/src/main/ets/managers/write.ets) -->
24
25	```ts
26    // Index.ets
27    import { write } from './write'
28    import { BusinessError } from '@kit.BasicServicesKit';
29    import { taskpool } from '@kit.ArkTS';
30    import { common } from '@kit.AbilityKit';
31
32    @Concurrent
33    async function concurrentTest(context: common.UIAbilityContext): Promise<boolean> {
34      let filePath1: string = context.filesDir + "/path1.txt"; // Application file path
35      let filePath2: string = context.filesDir + "/path2.txt";
36      // Write data to the file cyclically.
37      let fileList: Array<string> = [];
38      fileList.push(filePath1);
39      fileList.push(filePath2)
40      for (let i: number = 0; i < fileList.length; i++) {
41        write('Hello World!', fileList[i]).then(() => {
42          console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`);
43        }).catch((err: BusinessError) => {
44          console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`)
45          return false;
46        })
47      }
48      return true;
49    }
50	```
51  <!-- @[define_concurrent_function](https://gitee.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/ApplicationMultithreading/entry/src/main/ets/managers/IoIntensiveTaskDevelopment.ets) -->
52
532. Use **TaskPool** to execute the concurrent function with frequent intensive I/O operations. Specifically, call [execute()](../reference/apis-arkts/js-apis-taskpool.md#taskpoolexecute) to execute the tasks and process the scheduling result in the callback. For details about how to obtain **filePath1** and **filePath2** in the example, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths). When using context in TaskPool, it must be prepared outside the concurrent function and passed as an argument.
54
55    ```ts
56    // Index.ets
57    @Entry
58    @Component
59    struct Index {
60      @State message: string = 'Hello World';
61      build() {
62        Row() {
63          Column() {
64            Text(this.message)
65              .fontSize(50)
66              .fontWeight(FontWeight.Bold)
67              .onClick(() => {
68                let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
69
70                // Use TaskPool to execute the concurrent function with frequent I/O operations.
71                // In the case of a large array, the distribution of I/O intensive tasks can block the UI main thread. Therefore, multithreading is necessary.
72                taskpool.execute(concurrentTest, context).then(() => {
73                  // Process the scheduling result.
74                  console.info("taskpool: execute success")
75                })
76              })
77          }
78          .width('100%')
79        }
80        .height('100%')
81      }
82    }
83    ```
84    <!-- @[taskpool_execute_concurrent_function](https://gitee.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ApplicationMultithreadingDevelopment/ApplicationMultithreading/entry/src/main/ets/managers/IoIntensiveTaskDevelopment.ets) -->
85