openharmony 鸿蒙 taskpool-async-task-guide

2025-06-06 浏览 (1)

Specifying Task Concurrency with TaskPool

This section describes how to use TaskPool to manage asynchronous queues. It uses the operation of collection and processing of camera preview stream data as an example. This 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.

  1. Import the required modules.

    // Index.ets
    import { taskpool } from '@kit.ArkTS';
    import { BusinessError, emitter } from '@kit.BasicServicesKit';
    
  2. Define a continuous task.

    // Index.ets
    @Concurrent
    function collectFrame() {
       // Collect and process data.
       // Simulate the processing task, which is time consuming.
       et t = new Date().getTime()
       while (new Date().getTime() - t < 30000) {
         continue;
       }
    }
    
  3. Create an asynchronous queue and execute the collection task.

    // Index.ets
    @Entry
    @Component
    struct Index {
      sensorTask?: taskpool.LongTask
    
      build() {
        Column() {
          Text("HELLO WORLD")
            .id('HelloWorld')
            .fontSize(50)
            .fontWeight(FontWeight.Bold)
            .onClick(() => {
              // Create an asynchronous queue with a concurrency level of 5 and a queue capacity of 5.
              let asyncRunner:taskpool.AsyncRunner = new taskpool.AsyncRunner("async", 5, 5);
              // Trigger the collection task every second.
              setTimeout(() => {
                let task:taskpool.Task = new taskpool.Task(collectFrame);
                 asyncRunner.execute(task);
               }, 1000);
            })
        }
        .height('100%')
        .width('100%')
      }
    }
    

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkTS

harmony 鸿蒙Configuring arkOptions in build-profile.json5

harmony 鸿蒙Asynchronous Lock

harmony 鸿蒙Ark Bytecode File Format

harmony 鸿蒙Naming Conventions for Ark Bytecode Functions

harmony 鸿蒙Ark Bytecode Fundamentals

harmony 鸿蒙Overview of Ark Bytecode

harmony 鸿蒙Shared Container

harmony 鸿蒙Asynchronous Waiting

harmony 鸿蒙ArkTS Cross-Language Interaction

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/OgN2uj