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 16// [Start define_concurrent_function] 17import { write } from './write' 18import { BusinessError } from '@kit.BasicServicesKit'; 19import { taskpool } from '@kit.ArkTS'; 20import { common } from '@kit.AbilityKit'; 21 22@Concurrent 23async function concurrentTest(context: common.UIAbilityContext): Promise<boolean> { 24 let filePath1: string = context.filesDir + '/path1.txt'; // 应用文件路径 25 let filePath2: string = context.filesDir + '/path2.txt'; 26 // 循环写文件操作 27 let fileList: string[] = []; 28 fileList.push(filePath1); 29 fileList.push(filePath2) 30 for (let i: number = 0; i < fileList.length; i++) { 31 write('Hello World!', fileList[i]).then(() => { 32 console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); 33 }).catch((err: BusinessError) => { 34 console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) 35 return false; 36 }) 37 } 38 return true; 39} 40// [End define_concurrent_function] 41 42// [Start taskpool_execute_concurrent_function] 43@Entry 44@Component 45struct Index { 46 @State message: string = 'Hello World'; 47 48 build() { 49 Row() { 50 Column() { 51 Text(this.message) 52 .fontSize(50) 53 .fontWeight(FontWeight.Bold) 54 .onClick(() => { 55 let context = getContext() as common.UIAbilityContext; 56 // 使用TaskPool执行包含密集I/O的并发函数 57 // 数组较大时,I/O密集型任务任务分发也会抢占UI主线程,需要使用多线程能力 58 taskpool.execute(concurrentTest, context).then(() => { 59 // 调度结果处理 60 console.info('taskpool: execute success') 61 }) 62 this.message = 'success'; 63 }) 64 } 65 .width('100%') 66 } 67 .height('100%') 68 } 69} 70// [End taskpool_execute_concurrent_function]