• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Specifying Task Concurrency with TaskPool
2
3This section describes how to use TaskPool to create [asynchronous queues](../reference/apis-arkts/js-apis-taskpool.md#asyncrunner18). It uses the operation of collection and processing of camera preview stream data as an example.
4This operation is frequent and time consuming. If the camera captures data too quickly, earlier frames are discarded to ensure only the most recent frame is processed.
5
61. Import the required modules.
7
8   ```ts
9   // Index.ets
10   import { taskpool } from '@kit.ArkTS';
11   import { BusinessError, emitter } from '@kit.BasicServicesKit';
12   ```
13
142. Define a continuous task.
15
16   ```ts
17   // Index.ets
18   @Concurrent
19   function collectFrame() {
20      // Collect and process data.
21      // Simulate the processing task, which is time consuming.
22      let t = new Date().getTime()
23      while (new Date().getTime() - t < 30000) {
24        continue;
25      }
26   }
27   ```
28
293. Create an asynchronous queue and execute the collection task.
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             // Create an asynchronous queue with a concurrency level of 5 and a queue capacity of 5.
46             let asyncRunner:taskpool.AsyncRunner = new taskpool.AsyncRunner("async", 5, 5);
47             // Trigger the collection task every second.
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