1# TaskPool指定任务并发度场景 2 3此处提供使用TaskPool进行[异步队列](../reference/apis-arkts/js-apis-taskpool.md#asyncrunner18)的开发指导,以相机预览流采集数据处理的功能为例。 4由于处理过程是个频繁耗时任务,如果相机采集过快,就丢弃之前的采集数据,缓存最新的一帧数据处理。 5 61. 导入需要用到的模块。 7 8 ```ts 9 // Index.ets 10 import { taskpool } from '@kit.ArkTS'; 11 import { BusinessError, emitter } from '@kit.BasicServicesKit'; 12 ``` 13 142. 定义长时任务。 15 16 ```ts 17 // Index.ets 18 @Concurrent 19 function collectFrame() { 20 // 采集数据,并且进行处理 21 // 模拟处理过程,这里是个耗时任务 22 et t = new Date().getTime() 23 while (new Date().getTime() - t < 30000) { 24 continue; 25 } 26 } 27 ``` 28 293. 创建异步队列并执行采集任务。 30 31 ```ts 32 // Index.ets 33 @Entry 34 @Component 35 struct Index { 36 sensorTask?: taskpool.LongTask 37 38 build() { 39 Column() { 40 Text("HELLO WORLD") 41 .id('HelloWorld') 42 .fontSize(50) 43 .fontWeight(FontWeight.Bold) 44 .onClick(() => { 45 // 创建并发度为5的异步队列,等待队列个数为5。 46 let asyncRunner:taskpool.AsyncRunner = new taskpool.AsyncRunner("async", 5, 5); 47 // 每秒触发一次采集任务 48 setTimeout(() => { 49 let task:taskpool.Task = new taskpool.Task(collectFrame); 50 asyncRunner.execute(task); 51 }, 1000); 52 }) 53 } 54 .height('100%') 55 .width('100%') 56 } 57 } 58 ``` 59 60 61