• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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// 并发函数中使用自定义类或函数
17// 并发函数中使用自定义类或函数时需定义在不同文件,否则会被认为是闭包,如下例所示。
18import { taskpool } from '@kit.ArkTS';
19import { BusinessError } from '@kit.BasicServicesKit';
20import { testAdd, MyTestA, MyTestB } from './Test';
21
22function add(arg: number) {
23  return ++arg;
24}
25
26class TestA {
27  constructor(name: string) {
28    this.name = name;
29  }
30  name: string = 'ClassA';
31}
32
33class TestB {
34  static nameStr: string = 'ClassB';
35}
36
37@Concurrent
38function testFunc() {
39  // case1:在并发函数中直接调用同文件内定义的类或函数
40
41  // 直接调用同文件定义的函数add(),add飘红报错:
42  // Only imported variables and local variables can be used in @Concurrent decorated functions. <ArkTSCheck>
43  // add(1);
44  // 直接使用同文件定义的TestA构造,TestA飘红报错:
45  // Only imported variables and local variables can be used in @Concurrent decorated functions. <ArkTSCheck>
46  // let a = new TestA('aaa');
47  // 直接访问同文件定义的TestB的成员nameStr,TestB飘红报错:
48  // Only imported variables and local variables can be used in @Concurrent decorated functions. <ArkTSCheck>
49  // console.info('TestB name is: ' + TestB.nameStr);
50
51  // case2:在并发函数中调用定义在Test.ets文件并导入当前文件的类或函数
52
53  // 输出结果:res1 is: 2
54  console.info('res1 is: ' + testAdd(1));
55  let tmpStr = new MyTestA('TEST A');
56  // 输出结果:res2 is: TEST A
57  console.info('res2 is: ' + tmpStr.name);
58  // 输出结果:res3 is: MyTestB
59  console.info('res3 is: ' + MyTestB.nameStr);
60}
61
62
63@Entry
64@Component
65struct Index {
66  @State message: string = 'Hello World';
67
68  build() {
69    RelativeContainer() {
70      Text(this.message)
71        .id('HelloWorld')
72        .fontSize(50)
73        .fontWeight(FontWeight.Bold)
74        .alignRules({
75          center: { anchor: '__container__', align: VerticalAlign.Center },
76          middle: { anchor: '__container__', align: HorizontalAlign.Center }
77        })
78        .onClick(() => {
79          let task = new taskpool.Task(testFunc);
80          taskpool.execute(task).then(() => {
81            console.info('taskpool: execute task success!');
82          }).catch((e:BusinessError) => {
83            console.error(`taskpool: execute: Code: ${e.code}, message: ${e.message}`);
84          })
85          this.message = 'success';
86        })
87    }
88    .height('100%')
89    .width('100%')
90  }
91}
92