1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { write } from './write' 17import { BusinessError } from '@kit.BasicServicesKit'; 18import { taskpool } from '@kit.ArkTS'; 19import { common } from '@kit.AbilityKit'; 20 21@Concurrent 22async function concurrentTest(context: common.UIAbilityContext): Promise<boolean> { 23 let filePath1: string = context.filesDir + '/path1.txt'; // 应用文件路径 24 let filePath2: string = context.filesDir + '/path2.txt'; 25 // 循环写文件操作 26 let fileList: string[] = []; 27 fileList.push(filePath1); 28 fileList.push(filePath2) 29 for (let i: number = 0; i < fileList.length; i++) { 30 write('Hello World!', fileList[i]).then(() => { 31 console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); 32 }).catch((err: BusinessError) => { 33 console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) 34 return false; 35 }) 36 } 37 return true; 38} 39 40@Entry 41@Component 42struct Index { 43 @State message: string = 'Hello World'; 44 45 build() { 46 Row() { 47 Column() { 48 Text(this.message) 49 .fontSize(50) 50 .fontWeight(FontWeight.Bold) 51 .onClick(() => { 52 let context = getContext() as common.UIAbilityContext; 53 // 使用TaskPool执行包含密集I/O的并发函数 54 // 数组较大时,I/O密集型任务任务分发也会抢占UI主线程,需要使用多线程能力 55 taskpool.execute(concurrentTest, context).then(() => { 56 // 调度结果处理 57 console.info('taskpool: execute success') 58 }) 59 this.message = 'success'; 60 }) 61 } 62 .width('100%') 63 } 64 .height('100%') 65 } 66}