• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# TaskPool指定任务并发度场景
2<!--Kit: ArkTS-->
3<!--Subsystem: CommonLibrary-->
4<!--Owner: @lijiamin2025-->
5<!--Designer: @weng-changcheng-->
6<!--Tester: @kirl75; @zsw_zhushiwei-->
7<!--Adviser: @ge-yafang-->
8
9TaskPool支持使用异步队列来控制任务的并发度,能有效避免资源过载,减少任务阻塞,适用于网络请求、视频流处理和数据库操作等场景。
10
11此处提供使用TaskPool创建[异步队列](../reference/apis-arkts/js-apis-taskpool.md#asyncrunner18)的开发指导,以相机预览流采集数据处理的功能为例。
12由于处理过程是一个频繁且耗时的任务,当相机采集速度过快时,将丢弃之前的采集数据,仅保留最新的一帧数据进行处理。
13
141. 导入需要用到的模块。
15
16   ```ts
17   // Index.ets
18   import { taskpool } from '@kit.ArkTS';
19   import { BusinessError } from '@kit.BasicServicesKit';
20   ```
21
222. 定义耗时任务。
23
24   ```ts
25   // Index.ets
26   @Concurrent
27   function collectFrame() {
28      // 采集数据,并且进行处理
29      // 模拟处理过程,这里是个耗时任务
30      let t = new Date().getTime()
31      while (new Date().getTime() - t < 30000) {
32        continue;
33      }
34      console.info("collectFrame finished");
35   }
36   ```
37
383. 创建异步队列并执行采集任务。
39
40   ```ts
41   // Index.ets
42   @Entry
43   @Component
44   struct Index {
45     @State message: string = 'Hello World';
46
47     build() {
48       Row() {
49         Column() {
50           Text(this.message)
51             .fontSize(50)
52             .fontWeight(FontWeight.Bold)
53             .onClick(async () => {
54               // 创建并发度为5的异步队列,等待队列个数为5,当加入的任务数量超过5时,等待列表中处于队头的任务会被丢弃。
55               let asyncRunner:taskpool.AsyncRunner = new taskpool.AsyncRunner("async", 5, 5);
56               // 触发采集任务
57               for (let i = 0; i < 20; i++) {
58                 let task:taskpool.Task = new taskpool.Task(`async${i}`,collectFrame);
59                 asyncRunner.execute(task).then(() => {
60                   console.info("the current task name is " + task.name);
61                 }).catch((e:BusinessError) => {
62                   console.error("async: error is " + e);
63                 });
64               }
65               console.info("asyncRunner task finished");
66             })
67         }
68         .width('100%')
69       }
70       .height('100%')
71     }
72   }
73   ```
74
75
76