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 taskpool_handle_sync_task] 17import { worker } from '@kit.ArkTS'; 18import { taskpool } from '@kit.ArkTS'; 19 20// 步骤1: 定义并发函数,实现业务逻辑 21@Concurrent 22async function taskpoolFunc(num: number): Promise<number> { 23 // 根据业务逻辑实现相应的功能 24 let tmpNum: number = num + 100; 25 return tmpNum; 26} 27 28async function mainFunc(): Promise<void> { 29 // 步骤2: 创建任务并执行 30 let task1: taskpool.Task = new taskpool.Task(taskpoolFunc, 1); 31 let res1: number = await taskpool.execute(task1) as number; 32 let task2: taskpool.Task = new taskpool.Task(taskpoolFunc, res1); 33 let res2: number = await taskpool.execute(task2) as number; 34 // 步骤3: 对任务返回的结果进行操作 35 console.info('taskpool: task res1 is: ' + res1); 36 console.info('taskpool: task res2 is: ' + res2); 37} 38 39// [Start worker_handle_associated_sync_task] 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(async () => { 52 mainFunc(); 53 let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker2.ts'); 54 w.onmessage = (): void => { 55 // 接收Worker子线程的结果 56 } 57 w.onerror = (): void => { 58 // 接收Worker子线程的错误信息 59 } 60 // 向Worker子线程发送Set消息 61 w.postMessage({ 'type': 0, 'data': 'data' }); 62 // 向Worker子线程发送Get消息 63 w.postMessage({ 'type': 1 }); 64 // ... 65 // 根据实际业务,选择时机以销毁线程 66 w.terminate(); 67 this.message = 'success'; 68 }) 69 } 70 .width('100%') 71 } 72 .height('100%') 73 } 74} 75// [End worker_handle_associated_sync_task] 76// [End taskpool_handle_sync_task]